001package org.kuali.ole.select.controller;
002
003import org.apache.commons.lang.StringUtils;
004import org.apache.log4j.Logger;
005import org.kuali.ole.OLEConstants;
006import org.kuali.ole.describe.service.DocstoreHelperService;
007import org.kuali.ole.docstore.discovery.service.QueryService;
008import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
009import org.kuali.ole.docstore.model.bo.WorkBibDocument;
010import org.kuali.ole.docstore.model.bo.WorkEInstanceDocument;
011import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
012import org.kuali.ole.docstore.model.enums.DocType;
013import org.kuali.ole.docstore.model.xmlpojo.work.einstance.oleml.EHoldings;
014import org.kuali.ole.docstore.model.xmlpojo.work.einstance.oleml.InstanceCollection;
015import org.kuali.ole.docstore.model.xstream.work.oleml.WorkEHoldingOlemlRecordProcessor;
016import org.kuali.ole.docstore.model.xstream.work.oleml.WorkEInstanceOlemlRecordProcessor;
017import org.kuali.ole.pojo.OleBibRecord;
018import org.kuali.ole.pojo.OleEditorResponse;
019import org.kuali.ole.select.bo.*;
020import org.kuali.ole.select.businessobject.OleCopy;
021import org.kuali.ole.select.businessobject.OleDocstoreResponse;
022import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
023import org.kuali.ole.select.document.*;
024import org.kuali.ole.select.form.OLEEResourceRecordForm;
025import org.kuali.ole.service.OLEEResourceSearchService;
026import org.kuali.ole.service.OleLicenseRequestWebService;
027import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
028import org.kuali.rice.krad.service.BusinessObjectService;
029import org.kuali.rice.krad.service.KRADServiceLocator;
030import org.kuali.rice.krad.service.KualiRuleService;
031import org.kuali.rice.krad.uif.UifParameters;
032import org.kuali.rice.krad.uif.container.CollectionGroup;
033import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
034import org.kuali.rice.krad.uif.view.View;
035import org.kuali.rice.krad.util.GlobalVariables;
036import org.kuali.rice.krad.web.controller.TransactionalDocumentControllerBase;
037import org.kuali.rice.krad.web.form.DocumentFormBase;
038import org.kuali.rice.krad.web.form.TransactionalDocumentFormBase;
039import org.kuali.rice.krad.web.form.UifFormBase;
040import org.springframework.stereotype.Controller;
041import org.springframework.validation.BindingResult;
042import org.springframework.web.bind.annotation.ModelAttribute;
043import org.springframework.web.bind.annotation.RequestMapping;
044import org.springframework.web.bind.annotation.RequestMethod;
045import org.springframework.web.servlet.ModelAndView;
046
047import javax.servlet.http.HttpServletRequest;
048import javax.servlet.http.HttpServletResponse;
049import java.sql.Date;
050import java.util.*;
051
052/**
053 * Created with IntelliJ IDEA.
054 * User: srinivasane
055 * Date: 6/21/13
056 * Time: 12:25 PM
057 * To change this template use File | Settings | File Templates.
058 */
059@Controller
060@RequestMapping(value = "/oleERSController")
061public class OLEEResourceRecordController extends TransactionalDocumentControllerBase {
062
063
064    /**
065     * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
066     */
067    private static final Logger LOG = Logger.getLogger(OLEEResourceRecordController.class);
068
069    private OleLicenseRequestWebService oleLicenseRequestWebService = null;
070    private KualiRuleService kualiRuleService;
071    private BusinessObjectService businessObjectService;
072    private OLEEResourceSearchService oleEResourceSearchService = null;
073
074    /**
075     * This method will return new Instance of OLEEResourceRecordForm.
076     *
077     * @param request
078     * @return OLEEResourceRecordForm.
079     */
080    @Override
081    protected TransactionalDocumentFormBase createInitialForm(HttpServletRequest request) {
082        OLEEResourceRecordForm oleeResourceRecordForm = new OLEEResourceRecordForm();
083        oleeResourceRecordForm.setStatusDate(new Date(System.currentTimeMillis()).toString());
084        oleeResourceRecordForm.setDocumentDescription(OLEConstants.OLEEResourceRecord.NEW_E_RESOURCE_REC);
085        return oleeResourceRecordForm;
086    }
087
088    /**
089     * This method takes the initial request when click on E-Resource Record Screen.
090     *
091     * @param form
092     * @param result
093     * @param request
094     * @param response
095     * @return ModelAndView
096     */
097    @Override
098    @RequestMapping(params = "methodToCall=start")
099    public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
100                              HttpServletRequest request, HttpServletResponse response) {
101        LOG.debug("Start -- Start Method of OlePatronRecordForm");
102        OLEEResourceRecordForm oleeResourceRecordForm = (OLEEResourceRecordForm) form;
103        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleeResourceRecordForm.getDocument();
104        oleeResourceRecordDocument.setStatusDate(new Date(System.currentTimeMillis()).toString());
105        return super.start(oleeResourceRecordForm, result, request, response);
106    }
107
108    /**
109     * This method populates date of the eventlog object thereby adding to the existing list.
110     *
111     * @param uifForm
112     * @param result
113     * @param request
114     * @param response
115     * @return ModelAndView
116     */
117    @RequestMapping(params = "methodToCall=addEventLogLine")
118    public ModelAndView addEventLogLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
119                                        HttpServletRequest request, HttpServletResponse response) {
120        OLEEResourceRecordForm form = (OLEEResourceRecordForm) uifForm;
121        String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
122        CollectionGroup collectionGroup = form.getPostedView().getViewIndex().getCollectionGroupByPath(
123                selectedCollectionPath);
124        String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
125        Object eventObject = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath);
126        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) form.getDocument();
127        OLEEResourceEventLog oleERSEventLog = (OLEEResourceEventLog) eventObject;
128        oleERSEventLog.setEventType(OLEConstants.OleLicenseRequest.USER);
129        oleERSEventLog.setCurrentTimeStamp();
130        oleERSEventLog.setOleERSIdentifier(oleeResourceRecordDocument.getDocumentNumber());
131        return addLine(uifForm, result, request, response);
132    }
133
134    /**
135     * This method populates date of the eventlog object thereby adding to the existing list.
136     *
137     * @param uifForm
138     * @param result
139     * @param request
140     * @param response
141     * @return ModelAndView
142     */
143    @RequestMapping(params = "methodToCall=deleteEventLogLine")
144    public ModelAndView deleteEventLogLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
145                                           HttpServletRequest request, HttpServletResponse response) {
146        OLEEResourceRecordForm form = (OLEEResourceRecordForm) uifForm;
147        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) form.getDocument();
148        String selectedLineIndex = form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX);
149        OLEEResourceEventLog oleERSEventLog = oleeResourceRecordDocument.getOleERSEventLogs().get(Integer.parseInt(selectedLineIndex));
150        //getBusinessObjectService().delete(oleERSEventLog);
151        return deleteLine(form, result, request, response);
152    }
153
154    /**
155     * This method Creates the License Request Document and link to the E-Resource document
156     *
157     * @param form
158     * @param result
159     * @param request
160     * @param response
161     * @return ModelAndView
162     */
163    @RequestMapping(params = "methodToCall=performCreateLicenseRequest")
164    public ModelAndView performCreateLicenseRequest(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
165                                                    HttpServletRequest request, HttpServletResponse response) {
166        LOG.debug("performCreateLicenseRequest method starts");
167        OLEEResourceRecordForm oleeResourceRecordForm = (OLEEResourceRecordForm) form;
168        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleeResourceRecordForm.getDocument();
169        OleLicenseRequestBo oleLicenseRequestBo = getOleLicenseRequestService().createLicenseRequest(
170                oleeResourceRecordDocument.getDocumentNumber(), null);
171        OLEEResourceLicense oleeResourceLicense = new OLEEResourceLicense();
172        oleeResourceLicense.setLicenseDocumentNumber(oleLicenseRequestBo.getLicenseDocumentNumber());
173        oleeResourceLicense.setDocumentRouteHeaderValue(oleLicenseRequestBo.getDocumentRouteHeaderValue());
174       /* Map<String,String> searchCriteria = new HashMap<String,String>();
175        searchCriteria.put(OLEConstants.DOC_ID,oleLicenseRequestBo.getLicenseDocumentNumber());*/
176        /*DocumentRouteHeaderValue documentHeader= (DocumentRouteHeaderValue)  getBusinessObjectService().findByPrimaryKey
177                (DocumentRouteHeaderValue.class,searchCriteria);*/
178        /*DocumentRouteHeaderValue documentHeader= KEWServiceLocator.getRouteHeaderService().getRouteHeader(oleLicenseRequestBo.getLicenseDocumentNumber(), true);
179        oleLicenseRequestBo.setDocumentRouteHeaderValue(documentHeader);*/
180
181        List<OLEEResourceInstance> listOfERInstances = oleeResourceRecordDocument.getOleERSInstances();
182        List<OleLicenseRequestItemTitle> oleLicenseRequestItemTitles = new ArrayList<>();
183        for (OLEEResourceInstance oleeResourceInstance : listOfERInstances) {
184            OleLicenseRequestItemTitle oleLicenseRequestItemTitle = new OleLicenseRequestItemTitle();
185            oleLicenseRequestItemTitle.setItemUUID(oleeResourceInstance.getBibId());
186            oleLicenseRequestItemTitle.setOleLicenseRequestId(oleLicenseRequestBo.getOleLicenseRequestId());
187            oleLicenseRequestItemTitle.setOleLicenseRequestBo(oleLicenseRequestBo);
188            oleLicenseRequestItemTitles.add(oleLicenseRequestItemTitle);
189        }
190        oleLicenseRequestBo.setOleLicenseRequestItemTitles(oleLicenseRequestItemTitles);
191
192
193        oleeResourceLicense.setOleLicenseRequestBo(oleLicenseRequestBo);
194        oleeResourceRecordDocument.getOleERSLicenseRequests().add(oleeResourceLicense);
195
196        //oleeResourceRecordDocument.
197        return getUIFModelAndView(oleeResourceRecordForm);
198    }
199
200    /**
201     * Saves the document instance contained on the form
202     *
203     * @param form - document form base containing the document instance that will be saved
204     * @return ModelAndView
205     */
206    @Override
207    @RequestMapping(params = "methodToCall=save")
208    public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
209                             HttpServletRequest request, HttpServletResponse response) throws Exception {
210        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
211        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
212        oleeResourceRecordDocument.setStatusDate(oleERSform.getStatusDate().toString());
213        if (oleeResourceRecordDocument.getTitle().length() < 40) {
214            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(oleeResourceRecordDocument.getTitle());
215        } else {
216            String documentDescription = oleeResourceRecordDocument.getTitle().substring(0, 39);
217            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(documentDescription);
218        }
219        List<OLEMaterialTypeList> oleMaterialTypeList = oleeResourceRecordDocument.getOleMaterialTypes();
220        List<OLEFormatTypeList> oleFormatTypeLists = oleeResourceRecordDocument.getOleFormatTypes();
221        List<OLEContentTypes> oleContentTypeList = oleeResourceRecordDocument.getOleContentTypes();
222        List<String> instanceId = new ArrayList<String>();
223        /*boolean oleERSFlag = false;
224        oleERSFlag &= getKualiRuleService().applyRules(new OLEMaterialTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleMaterialTypes()));
225        oleERSFlag &= getKualiRuleService().applyRules(new OLEContentTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleContentTypes()));
226        if (oleERSFlag) {
227        return getUIFModelAndView(oleERSform);
228        }*/
229        boolean flag = false;
230        if (oleMaterialTypeList.size() == 0) {
231            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_MATERIAL_TYPES, OLEConstants.OLEEResourceRecord.MATERIAL_TYPE_REQUIRED, new String[]{"Material Type"});
232            flag = true;
233        }
234        if (oleFormatTypeLists.size() == 0) {
235            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_FORMAT_TYPES, OLEConstants.OLEEResourceRecord.FORMAT_TYPE_REQUIRED, new String[]{"Format Type"});
236            flag = true;
237        }
238        if (oleContentTypeList.size() == 0) {
239            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_CONTENT_TYPES, OLEConstants.OLEEResourceRecord.CONTENT_TYPE_REQUIRED, new String[]{"Content Type"});
240            flag = true;
241        }
242        if (flag) {
243            return getUIFModelAndView(oleERSform);
244        }
245        String fileName = oleeResourceRecordDocument.getDocumentNumber();
246        if (oleERSform.isCreateInstance()) {
247            getOleEResourceSearchService().getNewInstance(oleeResourceRecordDocument, fileName);
248            oleERSform.setCreateInstance(false);
249        }
250        oleERSform.setBibId(null);
251        oleERSform.setInstanceId(null);
252        oleERSform.setLinkInstance(false);
253        if (oleeResourceRecordDocument.getOleERSIdentifier() != null && !oleeResourceRecordDocument.getOleERSIdentifier().isEmpty()) {
254            oleeResourceRecordDocument = getOleEResourceSearchService().getNewOleERSDoc(oleeResourceRecordDocument);
255            Map<String, String> tempId = new HashMap<String, String>();
256            tempId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
257            OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
258            int instancesSize = tempDocument.getOleERSInstances().size();
259            int instanceSize = oleeResourceRecordDocument.getOleERSInstances().size();
260            if (tempDocument.iseInstanceFlag() && instancesSize > instanceSize && !oleERSform.isRemoveInstanceFlag()) {
261                super.reload(oleERSform, result, request, response);
262            }
263            oleERSform.setRemoveInstanceFlag(false);
264        }
265
266        return super.save(oleERSform, result, request, response);
267    }
268
269    /**
270     * Routes the document instance contained on the form
271     *
272     * @param form - document form base containing the document instance that will be routed
273     * @return ModelAndView
274     */
275    @RequestMapping(params = "methodToCall=route")
276    public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
277                              HttpServletRequest request, HttpServletResponse response) {
278        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
279        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
280        oleeResourceRecordDocument.setStatusDate(oleERSform.getStatusDate().toString());
281        if (oleeResourceRecordDocument.getTitle().length() < 40) {
282            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(oleeResourceRecordDocument.getTitle());
283        } else {
284            String documentDescription = oleeResourceRecordDocument.getTitle().substring(0, 39);
285            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(documentDescription);
286        }
287        List<OLEMaterialTypeList> oleMaterialTypeList = oleeResourceRecordDocument.getOleMaterialTypes();
288        List<OLEFormatTypeList> oleFormatTypeLists = oleeResourceRecordDocument.getOleFormatTypes();
289        List<OLEContentTypes> oleContentTypeList = oleeResourceRecordDocument.getOleContentTypes();
290        List<String> instanceId = new ArrayList<String>();
291        /*boolean oleERSFlag = false;
292        oleERSFlag &= getKualiRuleService().applyRules(new OLEMaterialTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleMaterialTypes()));
293        oleERSFlag &= getKualiRuleService().applyRules(new OLEContentTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleContentTypes()));
294        if (oleERSFlag) {
295        return getUIFModelAndView(oleERSform);
296        }*/
297        boolean flag = false;
298        if (oleMaterialTypeList.size() == 0) {
299            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_MATERIAL_TYPES, OLEConstants.OLEEResourceRecord.MATERIAL_TYPE_REQUIRED, new String[]{"Material Type"});
300            flag = true;
301        }
302        if (oleFormatTypeLists.size() == 0) {
303            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_FORMAT_TYPES, OLEConstants.OLEEResourceRecord.FORMAT_TYPE_REQUIRED, new String[]{"Format Type"});
304            flag = true;
305        }
306        if (oleContentTypeList.size() == 0) {
307            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_CONTENT_TYPES, OLEConstants.OLEEResourceRecord.CONTENT_TYPE_REQUIRED, new String[]{"Content Type"});
308            flag = true;
309        }
310        if (flag) {
311            return getUIFModelAndView(oleERSform);
312        }
313        String fileName = oleeResourceRecordDocument.getDocumentNumber();
314        if (oleERSform.isCreateInstance()) {
315            getOleEResourceSearchService().getNewInstance(oleeResourceRecordDocument, fileName);
316            oleERSform.setCreateInstance(false);
317        }
318        oleERSform.setBibId(null);
319        oleERSform.setInstanceId(null);
320        oleERSform.setLinkInstance(false);
321        if (oleeResourceRecordDocument.getOleERSIdentifier() != null && !oleeResourceRecordDocument.getOleERSIdentifier().isEmpty()) {
322            oleeResourceRecordDocument = getOleEResourceSearchService().getNewOleERSDoc(oleeResourceRecordDocument);
323            Map<String, String> tempId = new HashMap<String, String>();
324            tempId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
325            OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
326            int instancesSize = tempDocument.getOleERSInstances().size();
327            int instanceSize = oleeResourceRecordDocument.getOleERSInstances().size();
328            if (tempDocument.iseInstanceFlag() && instancesSize > instanceSize && !oleERSform.isRemoveInstanceFlag()) {
329                try {
330                    super.reload(oleERSform, result, request, response);
331                } catch (Exception e) {
332                    LOG.error(e.getMessage());
333                }
334            }
335            oleERSform.setRemoveInstanceFlag(false);
336        }
337        return super.route(oleERSform, result, request, response);
338    }
339
340    /**
341     * Performs the approve workflow action on the form document instance
342     *
343     * @param form - document form base containing the document instance that will be approved
344     * @return ModelAndView
345     */
346    @Override
347    @RequestMapping(params = "methodToCall=approve")
348    public ModelAndView approve(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
349                                HttpServletRequest request, HttpServletResponse response) throws Exception {
350        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
351        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
352        oleeResourceRecordDocument.setStatusDate(oleERSform.getStatusDate().toString());
353        if (oleeResourceRecordDocument.getTitle().length() < 40) {
354            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(oleeResourceRecordDocument.getTitle());
355        } else {
356            String documentDescription = oleeResourceRecordDocument.getTitle().substring(0, 39);
357            oleeResourceRecordDocument.getDocumentHeader().setDocumentDescription(documentDescription);
358        }
359        List<OLEMaterialTypeList> oleMaterialTypeList = oleeResourceRecordDocument.getOleMaterialTypes();
360        List<OLEFormatTypeList> oleFormatTypeLists = oleeResourceRecordDocument.getOleFormatTypes();
361        List<OLEContentTypes> oleContentTypeList = oleeResourceRecordDocument.getOleContentTypes();
362        List<String> instanceId = new ArrayList<String>();
363        /*boolean oleERSFlag = false;
364        oleERSFlag &= getKualiRuleService().applyRules(new OLEMaterialTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleMaterialTypes()));
365        oleERSFlag &= getKualiRuleService().applyRules(new OLEContentTypeEvent(oleeResourceRecordDocument,oleeResourceRecordDocument.getOleContentTypes()));
366        if (oleERSFlag) {
367        return getUIFModelAndView(oleERSform);
368        }*/
369        boolean flag = false;
370        if (oleMaterialTypeList.size() == 0) {
371            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_MATERIAL_TYPES, OLEConstants.OLEEResourceRecord.MATERIAL_TYPE_REQUIRED, new String[]{"Material Type"});
372            flag = true;
373        }
374        if (oleFormatTypeLists.size() == 0) {
375            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_FORMAT_TYPES, OLEConstants.OLEEResourceRecord.FORMAT_TYPE_REQUIRED, new String[]{"Format Type"});
376            flag = true;
377        }
378        if (oleContentTypeList.size() == 0) {
379            GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_CONTENT_TYPES, OLEConstants.OLEEResourceRecord.CONTENT_TYPE_REQUIRED, new String[]{"Content Type"});
380            flag = true;
381        }
382        if (flag) {
383            return getUIFModelAndView(oleERSform);
384        }
385        String fileName = oleeResourceRecordDocument.getDocumentNumber();
386        if (oleERSform.isCreateInstance()) {
387            getOleEResourceSearchService().getNewInstance(oleeResourceRecordDocument, fileName);
388            oleERSform.setCreateInstance(false);
389        }
390        oleERSform.setBibId(null);
391        oleERSform.setInstanceId(null);
392        oleERSform.setLinkInstance(false);
393        if (oleeResourceRecordDocument.getOleERSIdentifier() != null && !oleeResourceRecordDocument.getOleERSIdentifier().isEmpty()) {
394            oleeResourceRecordDocument = getOleEResourceSearchService().getNewOleERSDoc(oleeResourceRecordDocument);
395            Map<String, String> tempId = new HashMap<String, String>();
396            tempId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
397            OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
398            int instancesSize = tempDocument.getOleERSInstances().size();
399            int instanceSize = oleeResourceRecordDocument.getOleERSInstances().size();
400            if (tempDocument.iseInstanceFlag() && instancesSize > instanceSize && !oleERSform.isRemoveInstanceFlag()) {
401                try {
402                    super.reload(oleERSform, result, request, response);
403                } catch (Exception e) {
404                    LOG.error(e.getMessage());
405                }
406            }
407            oleERSform.setRemoveInstanceFlag(false);
408        }
409        return super.approve(oleERSform, result, request, response);
410    }
411
412    /*@Override
413    @RequestMapping(params = "methodToCall=cancel")
414    public ModelAndView cancel(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
415                               HttpServletRequest request, HttpServletResponse response) {
416        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
417        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
418        if (oleeResourceRecordDocument != null) {
419            Map<String, String> criteriaStatusIdMap = new HashMap<String, String>();
420            criteriaStatusIdMap.put(OLEConstants.OLEEResourceRecord.STATUS_NAME, OLEConstants.OLEEResourceRecord.CANCELED);
421            List<OLEEResourceStatus> oleERSStatusList = (List<OLEEResourceStatus>) getBusinessObjectService().findMatching(OLEEResourceStatus.class, criteriaStatusIdMap);
422            if (oleERSStatusList.size() > 0) {
423                OLEEResourceStatus oleERSStatus = oleERSStatusList.get(0);
424                if (oleERSStatus != null) {
425                    oleeResourceRecordDocument.setStatusId(oleERSStatus.getOleEResourceStatusId());
426                    oleeResourceRecordDocument.setStatusName(oleERSStatus.getOleEResourceStatusName());
427                }
428            }
429        }
430        try {
431            save(oleERSform, result, request, response);
432        } catch (Exception e) {
433            throw new RuntimeException(e);
434        }
435        return super.cancel(oleERSform, result, request, response);
436    }
437*/
438
439    /**
440     * Create E-Instance document instance contained on the form
441     *
442     * @param form - document form base containing the document instance that will be routed
443     * @return ModelAndView
444     */
445    @RequestMapping(params = "methodToCall=createInstance")
446    public ModelAndView createInstance(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
447                                       HttpServletRequest request, HttpServletResponse response) {
448        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
449        oleERSform.setSelectFlag(true);
450        oleERSform.setLinkInstance(false);
451        oleERSform.setCreateInstance(true);
452        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
453        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
454    }
455
456    /**
457     * close the popup in instance tab
458     *
459     * @param form - document form base containing the document instance that will be routed
460     * @return ModelAndView
461     */
462    @RequestMapping(params = "methodToCall=closePopup")
463    public ModelAndView closePopup(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
464                                   HttpServletRequest request, HttpServletResponse response) {
465        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
466        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
467    }
468
469    /**
470     * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
471     * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
472     *
473     * @param instanceIdsList
474     * @return List<WorkBibDocument>
475     */
476    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList, String docType) {
477        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
478        for (String instanceId : instanceIdsList) {
479            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
480            instanceIdMap.put(docType, instanceId);
481            instanceIdMapList.add(instanceIdMap);
482        }
483
484        QueryService queryService = QueryServiceImpl.getInstance();
485        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
486        try {
487            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
488        } catch (Exception ex) {
489            // TODO Auto-generated catch block
490            ex.printStackTrace();
491        }
492        return workBibDocuments;
493    }
494
495    /**
496     * Called by the delete line action for a model collection. Method
497     * determines which collection the action was selected for and the line
498     * index that should be removed, then invokes the view helper service to
499     * process the action
500     */
501    @RequestMapping(method = RequestMethod.POST, params = "methodToCall=removeInstance")
502    public ModelAndView removeInstance(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
503                                       HttpServletRequest request, HttpServletResponse response) {
504
505        OLEEResourceRecordForm oleEResourceRecordForm = (OLEEResourceRecordForm) uifForm;
506        OLEEResourceRecordDocument oleEResourceRecordDocument = (OLEEResourceRecordDocument) oleEResourceRecordForm.getDocument();
507        String selectedCollectionPath = oleEResourceRecordForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
508        if (StringUtils.isBlank(selectedCollectionPath)) {
509            throw new RuntimeException(OLEConstants.OLEEResourceRecord.BLANK_SELECTED_INDEX);
510        }
511        int selectedLineIndex = -1;
512        String selectedLine = oleEResourceRecordForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX);
513        if (StringUtils.isNotBlank(selectedLine)) {
514            OLEEResourceInstance oleERSInstance = oleEResourceRecordDocument.getOleERSInstances().get(Integer.parseInt(selectedLine));
515            Map removePOMap = new HashMap();
516            removePOMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_INSTANCE_ID, oleERSInstance.getInstanceId());
517            removePOMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSInstance.getOleERSIdentifier());
518            List<OLEEResourcePO> oleERSPOs = (List<OLEEResourcePO>) KRADServiceLocator.getBusinessObjectService().findMatching(OLEEResourcePO.class, removePOMap);
519            if (oleERSPOs.size() > 0) {
520                for (OLEEResourcePO oleeResourcePO : oleERSPOs) {
521                    removePOMap.remove(OLEConstants.OLEEResourceRecord.ERESOURCE_INSTANCE_ID);
522                    removePOMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSInstance.getOleERSIdentifier());
523                    removePOMap.put(OLEConstants.OLEEResourceRecord.PO_ID, oleeResourcePO.getOlePOItemId());
524                    List<OLEEResourceInvoices> oleERSInvoices = (List<OLEEResourceInvoices>) KRADServiceLocator.getBusinessObjectService().findMatching(OLEEResourceInvoices.class, removePOMap);
525                    if (oleERSInvoices.size() > 0) {
526                        getBusinessObjectService().delete(oleERSInvoices);
527                    }
528                }
529                getBusinessObjectService().delete(oleERSPOs);
530            }
531            if (oleERSInstance.getInstanceId().contains(OLEConstants.WEN)) {
532                try {
533                    DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
534                    String eInstanceContent = docstoreHelperService.getDocstoreData(oleERSInstance.getInstanceId());
535                    WorkEInstanceOlemlRecordProcessor workEInstanceOlemlRecordProcessor = new WorkEInstanceOlemlRecordProcessor();
536                    WorkEHoldingOlemlRecordProcessor workEHoldingOlemlRecordProcessor = new WorkEHoldingOlemlRecordProcessor();
537                    InstanceCollection instanceCollection = workEInstanceOlemlRecordProcessor.fromXML(eInstanceContent);
538                    EHoldings eHoldings = instanceCollection.getEInstance().get(0).getEHoldings();
539                    eHoldings.setEResourceId(null);
540                    docstoreHelperService.updateInstanceRecord(eHoldings.getHoldingsIdentifier(), DocType.EHOLDINGS.getCode(), workEHoldingOlemlRecordProcessor.toXML(eHoldings));
541                } catch (Exception e) {
542                    LOG.error("Illegal exception while updating instance record" + e.getMessage());
543
544                }
545            }
546            List<OLEEResourcePO> oleERSPOList = (List<OLEEResourcePO>) KRADServiceLocator.getBusinessObjectService().findAll(OLEEResourcePO.class);
547            oleEResourceRecordDocument.setOleERSPOItems(oleERSPOList);
548            List<OLEEResourceInvoices> oleERSInvoiceList = (List<OLEEResourceInvoices>) KRADServiceLocator.getBusinessObjectService().findAll(OLEEResourceInvoices.class);
549            oleEResourceRecordDocument.setOleERSInvoices(oleERSInvoiceList);
550            selectedLineIndex = Integer.parseInt(selectedLine);
551            OLEEResourceEventLog oleEResourceEventLog = new OLEEResourceEventLog();
552            oleEResourceEventLog.setCurrentTimeStamp();
553            oleEResourceEventLog.setEventUser(GlobalVariables.getUserSession().getPrincipalName());
554            oleEResourceEventLog.setEventNote(oleERSInstance.getInstanceTitle() + OLEConstants.OLEEResourceRecord.INSTANCE_ID_REMOVE_NOTE + oleERSInstance.getInstanceId() + OLEConstants.OLEEResourceRecord.REMOVE_NOTE);
555            oleEResourceEventLog.setEventType(OLEConstants.OLEEResourceRecord.SYSTEM);
556            oleEResourceRecordDocument.getOleERSEventLogs().add(oleEResourceEventLog);
557
558        }
559        if (selectedLineIndex == -1) {
560            throw new RuntimeException(OLEConstants.OLEEResourceRecord.BLANK_SELECTED_INDEX);
561        }
562        oleEResourceRecordForm.setRemoveInstanceFlag(true);
563        View view = oleEResourceRecordForm.getPostedView();
564        view.getViewHelperService().processCollectionDeleteLine(view, oleEResourceRecordForm, selectedCollectionPath,
565                selectedLineIndex);
566
567        return getUIFModelAndView(oleEResourceRecordForm);
568    }
569
570
571    /**
572     * This method returns the object of OleLicesneRequestService
573     *
574     * @return oleLicenseRequestService
575     */
576    public OleLicenseRequestWebService getOleLicenseRequestService() {
577        if (oleLicenseRequestWebService == null) {
578            oleLicenseRequestWebService = GlobalResourceLoader.getService(OLEConstants.OleLicenseRequest.HELPER_SERVICE);
579        }
580        return oleLicenseRequestWebService;
581    }
582
583    public KualiRuleService getKualiRuleService() {
584        if (kualiRuleService == null) {
585            kualiRuleService = GlobalResourceLoader.getService(OLEConstants.KUALI_RULE_SERVICE);
586        }
587        return kualiRuleService;
588    }
589
590    public BusinessObjectService getBusinessObjectService() {
591        if (businessObjectService == null) {
592            businessObjectService = KRADServiceLocator.getBusinessObjectService();
593        }
594        return businessObjectService;
595    }
596
597    public OLEEResourceSearchService getOleEResourceSearchService() {
598        if (oleEResourceSearchService == null) {
599            oleEResourceSearchService = GlobalResourceLoader.getService(OLEConstants.OLEEResourceRecord.ERESOURSE_SEARCH_SERVICE);
600        }
601        return oleEResourceSearchService;
602    }
603
604
605    /**
606     * Edit Default Coverage date for E-Instance
607     *
608     * @param form - document form base containing the document instance that will be routed
609     * @return ModelAndView
610     */
611    @RequestMapping(params = "methodToCall=editDefaultCoverage")
612    public ModelAndView editDefaultCoverage(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
613                                            HttpServletRequest request, HttpServletResponse response) {
614        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
615        oleERSform.setCoverageFlag(true);
616        oleERSform.setPerpetualAccessFlag(false);
617        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
618        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
619    }
620
621    /**
622     * Edit Default Perpetual date for E-Instance
623     *
624     * @param form - document form base containing the document instance that will be routed
625     * @return ModelAndView
626     */
627    @RequestMapping(params = "methodToCall=editDefaultPerpetualAccess")
628    public ModelAndView editDefaultPerpetualAccess(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
629                                                   HttpServletRequest request, HttpServletResponse response) {
630        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
631        oleERSform.setCoverageFlag(false);
632        oleERSform.setPerpetualAccessFlag(true);
633        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
634        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
635    }
636
637    /**
638     * close the popup in instance tab
639     *
640     * @param form - document form base containing the document instance that will be routed
641     * @return ModelAndView
642     */
643    @RequestMapping(params = "methodToCall=closeCoverageOrPerpetualAccessDate")
644    public ModelAndView closeCoverageOrPerpetualAccessDate(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
645                                                           HttpServletRequest request, HttpServletResponse response) {
646        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
647        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
648    }
649
650    /**
651     * refresh the instance tab
652     *
653     * @param form - document form base containing the document instance that will be routed
654     * @return ModelAndView
655     */
656    @RequestMapping(params = "methodToCall=refreshDefaultDate")
657    public ModelAndView refreshDefaultDate(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
658                                           HttpServletRequest request, HttpServletResponse response) {
659        OLEEResourceRecordForm oleERSform = (OLEEResourceRecordForm) form;
660        OLEEResourceRecordDocument oleeResourceRecordDocument = (OLEEResourceRecordDocument) oleERSform.getDocument();
661        getOleEResourceSearchService().getDefaultCovergeDate(oleeResourceRecordDocument);
662        getOleEResourceSearchService().getDefaultPerpetualAccessDate(oleeResourceRecordDocument);
663        return getUIFModelAndView(oleERSform, OLEConstants.OLEEResourceRecord.E_RES_INSTANCE_TAB);
664    }
665
666}