View Javadoc
1   package org.kuali.ole.describe.controller;
2   
3   import org.apache.commons.collections.CollectionUtils;
4   import org.apache.commons.lang3.StringUtils;
5   import org.apache.log4j.Logger;
6   import org.apache.solr.client.solrj.SolrServerException;
7   import org.kuali.ole.DocumentUniqueIDPrefix;
8   import org.kuali.asr.service.ASRHelperServiceImpl;
9   import org.kuali.ole.OLEConstants;
10  import org.kuali.ole.OLEParameterConstants;
11  import org.kuali.ole.deliver.bo.ASRItem;
12  import org.kuali.ole.deliver.bo.OLELoanIntransitRecordHistory;
13  import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
14  import org.kuali.ole.deliver.bo.OleLoanDocument;
15  import org.kuali.ole.deliver.calendar.service.DateUtil;
16  import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
17  import org.kuali.ole.describe.bo.DocumentSelectionTree;
18  import org.kuali.ole.describe.bo.DocumentTreeNode;
19  import org.kuali.ole.describe.bo.InstanceEditorFormDataHandler;
20  import org.kuali.ole.describe.bo.OleInstanceItemType;
21  import org.kuali.ole.describe.form.EditorForm;
22  import org.kuali.ole.describe.form.WorkBibMarcForm;
23  import org.kuali.ole.describe.form.WorkInstanceOlemlForm;
24  import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
25  import org.kuali.ole.docstore.common.client.DocstoreClient;
26  import org.kuali.ole.docstore.common.document.*;
27  import org.kuali.ole.docstore.common.document.HoldingsTree;
28  import org.kuali.ole.docstore.common.document.content.enums.DocCategory;
29  import org.kuali.ole.docstore.common.document.content.enums.DocFormat;
30  import org.kuali.ole.docstore.common.document.content.enums.DocType;
31  import org.kuali.ole.docstore.common.document.content.instance.*;
32  import org.kuali.ole.docstore.common.document.content.instance.Item;
33  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
34  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
35  import org.kuali.ole.docstore.common.exception.DocstoreException;
36  import org.kuali.ole.docstore.common.exception.DocstoreResources;
37  import org.kuali.ole.docstore.common.exception.DocstoreValidationException;
38  import org.kuali.ole.docstore.engine.client.DocstoreLocalClient;
39  import org.kuali.ole.select.bo.OLEDonor;
40  import org.kuali.ole.select.bo.OLELinkPurapDonor;
41  import org.kuali.ole.select.businessobject.OleCopy;
42  import org.kuali.ole.select.document.OlePurchaseOrderDocument;
43  import org.kuali.ole.sys.context.SpringContext;
44  import org.kuali.ole.utility.Constants;
45  import org.kuali.rice.core.api.config.property.ConfigurationService;
46  import org.kuali.rice.core.api.datetime.DateTimeService;
47  import org.kuali.rice.core.api.util.RiceConstants;
48  import org.kuali.rice.core.api.util.tree.Node;
49  import org.kuali.rice.kim.api.permission.PermissionService;
50  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
51  import org.kuali.rice.krad.service.BusinessObjectService;
52  import org.kuali.rice.krad.service.KRADServiceLocator;
53  import org.kuali.rice.krad.uif.UifParameters;
54  import org.kuali.rice.krad.util.GlobalVariables;
55  import org.kuali.rice.krad.util.KRADConstants;
56  
57  import javax.servlet.http.HttpServletRequest;
58  import java.text.DateFormat;
59  import java.text.Format;
60  import java.text.ParseException;
61  import java.text.SimpleDateFormat;
62  import java.util.*;
63  
64  /**
65   * Created with IntelliJ IDEA.
66   * User: sambasivam
67   * Date: 1/9/14
68   * Time: 5:01 PM
69   * To change this template use File | Settings | File Templates.
70   */
71  public class WorkItemOlemlEditor extends AbstractEditor {
72  
73      private static final Logger LOG = Logger.getLogger(WorkItemOlemlEditor.class);
74      HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
75      ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
76      ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
77      BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
78  
79      private static WorkItemOlemlEditor workItemOlemlEditor = null;
80      private InstanceEditorFormDataHandler instanceEditorFormDataHandler = null;
81  
82      DocstoreClient docstoreClient = getDocstoreLocalClient();
83  
84      private OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService;
85  
86      private OleDeliverRequestDocumentHelperServiceImpl getOleDeliverRequestDocumentHelperService() {
87          if (oleDeliverRequestDocumentHelperService == null) {
88              oleDeliverRequestDocumentHelperService = new OleDeliverRequestDocumentHelperServiceImpl();
89          }
90          return oleDeliverRequestDocumentHelperService;
91      }
92  
93      public static WorkItemOlemlEditor getInstance() {
94          if (workItemOlemlEditor == null) {
95              workItemOlemlEditor = new WorkItemOlemlEditor();
96          }
97          return workItemOlemlEditor;
98      }
99  
100     private WorkItemOlemlEditor() {
101 
102     }
103 
104     @Override
105     public EditorForm loadDocument(EditorForm editorForm) {
106         WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
107         String directory = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(org.kuali.ole.sys.OLEConstants.EXTERNALIZABLE_HELP_URL_KEY);
108         editorForm.setExternalHelpUrl(directory+"/reference/webhelp/OLE/content/ch04s01.html#_Item");
109         editorForm.setHeaderText("Item");
110         editorForm.setItem(true);
111         editorForm.setHasLink(true);
112         String parameter = getParameter(OLEConstants.APPL_ID_OLE, OLEConstants.DESC_NMSPC, OLEConstants
113                 .DESCRIBE_COMPONENT, OLEConstants.ITEM_LOCATION_DISCLOSURE);
114         editorForm.setOpenLocation(Boolean.valueOf(parameter));
115         String shelvingOrder = getParameter(OLEConstants.APPL_ID_OLE, OLEConstants.DESC_NMSPC, OLEConstants
116                 .DESCRIBE_COMPONENT, OLEConstants.ITEM_SUPRESS_SHELVINGORDER);
117         if(Boolean.valueOf(shelvingOrder)){
118             editorForm.setSupressItemShelving(false);
119         }else{
120             editorForm.setSupressItemShelving(true);
121         }
122         String bibId = editorForm.getBibId();
123         String holdingsId = editorForm.getInstanceId();
124         String docId = editorForm.getDocId();
125         OleHoldings oleHoldings = new OleHoldings();
126         String docStoreData = null;
127         List<BibTree> bibTreeList = new ArrayList<>();
128         Date date = new Date();
129         SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE+" HH:mm:ss");
130         String dateStr = sdf.format(date);
131         BibTree bibTree = null;
132         try {
133             bibTree = docstoreClient.retrieveBibTree(bibId);
134             bibTreeList.add(bibTree);
135             workInstanceOlemlForm.setBibTreeList(bibTreeList);
136             if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bibTree.getBib().getFormat())) {
137                 String titleField = bibTree.getBib().getTitle() + " / " + bibTree.getBib().getAuthor() + " / " + DocumentUniqueIDPrefix.getDocumentId(bibTree.getBib().getId());
138                 editorForm.setTitle(titleField);
139             }
140             Holdings holdings = docstoreClient.retrieveHoldings(holdingsId);
141             oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
142             workInstanceOlemlForm.setSelectedHolding(oleHoldings);
143         } catch (DocstoreException e) {
144             LOG.error(e);
145             DocstoreException docstoreException = (DocstoreException) e;
146             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
147                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
148             } else {
149                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
150             }
151             return workInstanceOlemlForm;
152         } catch (Exception e) {
153             LOG.error("Exception ", e);
154             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
155         }
156 
157         try {
158             if (StringUtils.isNotEmpty(docId)) {
159                 editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(docId));
160                 org.kuali.ole.docstore.common.document.Item itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
161                 docStoreData = itemDocument.getContent();
162                 Item item = itemOlemlRecordProcessor.fromXML(docStoreData);
163                 ensureAccessInformation(item);
164                 //TODO : set additional attributes
165                 String itemStatus = null;
166                 if (item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null) {
167                     itemStatus = item.getItemStatus().getCodeValue();
168                     workInstanceOlemlForm.setOldItemStatus(itemStatus);
169                 }
170 
171                 String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "ITEM_STATUS_READONLY");
172                 String[] itemArray = itemProperty.split(",");
173                 for (String status : itemArray) {
174                     if (status.equalsIgnoreCase(itemStatus)) {
175                         workInstanceOlemlForm.setItemStatusNonEditable(true);
176                         break;
177                     }
178                     workInstanceOlemlForm.setItemStatusNonEditable(false);
179                 }
180 
181                 itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "ITEM_BARCODE_READONLY");
182                 String[] itemArrayBarcode = itemProperty.split(",");
183                 for (String status : itemArrayBarcode) {
184                     if (status.equalsIgnoreCase(itemStatus)) {
185                         workInstanceOlemlForm.setItemBarcodeNonEditable(true);
186                         break;
187                     }
188                     workInstanceOlemlForm.setItemBarcodeNonEditable(false);
189                 }
190 
191                 itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
192                 boolean editable;
193                 if (itemProperty != null) {
194                     editable = Boolean.valueOf(itemProperty);
195                     workInstanceOlemlForm.setHoldingsDataInItemReadOnly(editable);
196                 }
197                 editorForm.setStaffOnlyFlagForItem(itemDocument.isStaffOnly());
198                 editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
199                 editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
200                 editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
201                 editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
202 
203                 List<Note> notes = ensureAtleastOneNote(item.getNote());
204                 item.setNote(notes);
205                 List<DonorInfo> donorInfos = ensureAtleastOneDonor(item.getDonorInfo());
206                 item.setDonorInfo(donorInfos);
207                 ensureAccessInformation(item);
208                 workInstanceOlemlForm.setSelectedItem(item);
209                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
210                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
211                 if (item.getAccessInformation()!=null && StringUtils.isNotEmpty(item.getAccessInformation().getBarcode())) {
212                     Map map = new HashMap();
213                     map.put("itemBarcode", item.getAccessInformation().getBarcode());
214                     List<OLELoanIntransitRecordHistory> oleLoanIntransitRecordHistories = (List<OLELoanIntransitRecordHistory>) KRADServiceLocator.getBusinessObjectService().findMatching(OLELoanIntransitRecordHistory.class, map);
215                     if (CollectionUtils.isNotEmpty(oleLoanIntransitRecordHistories)) {
216                         editorForm.setOleLoanIntransitRecordHistories(oleLoanIntransitRecordHistories);
217                     }
218                 }
219                 if (editorForm.getEditable().equalsIgnoreCase("false")) {
220                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
221                 } else {
222                     boolean hasPermission = canEditItem(GlobalVariables.getUserSession().getPrincipalId());
223                     if (hasPermission) {
224                         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
225                     } else {
226                         editorForm.setHideFooter(false);
227                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_ITEM);
228                     }
229                 }
230             } else {
231 
232                 Item item = new Item();
233                 String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
234                 String[] itemArray = null;
235                 if (itemProperty != null) {
236                     itemArray = itemProperty.split(",");
237                 }
238                 if (itemArray != null) {
239                     for (String status : itemArray) {
240                         if (status.equalsIgnoreCase("TRUE")) {
241                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
242                         } else if (status.equalsIgnoreCase("FALSE")) {
243                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
244                         }
245                     }
246                 }
247                 List<Note> notes = ensureAtleastOneNote(item.getNote());
248                 item.setNote(notes);
249                 List<DonorInfo> donorInfos = ensureAtleastOneDonor(item.getDonorInfo());
250                 item.setDonorInfo(donorInfos);
251                 ensureAccessInformation(item);
252                 workInstanceOlemlForm.setSelectedItem(item);
253                 String itemTypeCode = getParameter(OLEConstants.APPL_ID_OLE, OLEConstants.DESC_NMSPC, OLEConstants
254                         .DESCRIBE_COMPONENT, OLEConstants.DEFAULT_ITEM_TYPE_CODE);
255                 if(StringUtils.isNotBlank(itemTypeCode)){
256                     Map map = new HashMap();
257                     map.put("instanceItemTypeCode", itemTypeCode);
258                     List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) KRADServiceLocator.getBusinessObjectService().findMatching(OleInstanceItemType.class, map);
259                     if (oleInstanceItemTypeList.size() > 0) {
260                         ItemType type = new ItemType();
261                         OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
262                         type.setCodeValue(oleInstanceItemType.getInstanceItemTypeCode());
263                         type.setFullValue(oleInstanceItemType.getInstanceItemTypeName());
264                         workInstanceOlemlForm.getSelectedItem().setItemType(type);
265                     }
266                 }
267                 this.addItemInformation(editorForm);
268                 editorForm.setStaffOnlyFlagForItem(false);
269                 editorForm.setItemCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
270                 editorForm.setItemCreatedDate(dateStr);
271                 editorForm.setItemUpdatedBy(null);
272                 editorForm.setItemUpdatedDate(null);
273                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
274                 boolean hasPermission = canCreateItem(GlobalVariables.getUserSession().getPrincipalId());
275                 if (hasPermission) {
276                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
277                             "item.details.new.message");
278                 } else {
279                     editorForm.setHideFooter(false);
280                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_CREATE_ITEM);
281                 }
282                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
283             }
284         } catch (DocstoreException e) {
285             LOG.error(e);
286             DocstoreException docstoreException = (DocstoreException) e;
287             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
288                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
289             } else {
290                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
291             }
292             return workInstanceOlemlForm;
293         } catch (Exception e) {
294             LOG.error("Exception ", e);
295             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
296         }
297         return workInstanceOlemlForm;
298     }
299 
300     private void ensureAccessInformation(Item item) {
301         if(item.getAccessInformation() == null) {
302             AccessInformation accessInformation = new AccessInformation();
303             Uri uri = new Uri();
304             uri.setValue("");
305             uri.setResolvable("");
306             accessInformation.setUri(uri);
307             item.setAccessInformation(accessInformation);
308         }
309     }
310 
311     @Override
312     public EditorForm saveDocument(EditorForm editorForm) {
313         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
314         Item itemData = workInstanceOlemlForm.getSelectedItem();
315         Date date = new Date();
316         SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
317         String dateStr = sdf.format(date);
318         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
319         String docId = editorForm.getDocId();
320         String instanceId = editorForm.getInstanceId();
321         String editorMessage = "";
322         String callNumber;
323         String prefix;
324         Bib bib = null;
325         int noOfPieces = 0;
326         boolean isExceedMaxCount = false;
327         boolean isNoOfPiecesCount = false;
328 //        editorForm.setHeaderText("Instance Editor (Item)- OLEML Format");
329         editorForm.setHeaderText("Item");
330         editorForm.setItem(true);
331         try {
332             bib = docstoreClient.retrieveBib(editorForm.getBibId());
333             if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bib.getFormat())) {
334                 String titleField = bib.getTitle() + " / " + bib.getAuthor() + " / " + DocumentUniqueIDPrefix.getDocumentId(bib.getId());
335                 editorForm.setTitle(titleField);
336             }
337         } catch (DocstoreException e) {
338             LOG.error(e);
339             DocstoreException docstoreException = (DocstoreException) e;
340             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
341                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
342             } else {
343                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
344             }
345             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
346             return workInstanceOlemlForm;
347         } catch (Exception e) {
348             LOG.error("Exception ", e);
349             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response", e.getMessage());
350         }
351 
352         try {
353             if (StringUtils.isNotEmpty(docId)) {
354                 //Item itemData = workInstanceOlemlForm.getSelectedItem();
355                 if (editorForm.getItemStatusSelection().equals("true")) {
356                     Format formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
357                     itemData.setItemStatusEffectiveDate(formatter.format(new Date()));
358                 }
359 
360                 if (!itemData.isClaimsReturnedFlag()) {
361                     itemData.setClaimsReturnedNote(null);
362                     itemData.setClaimsReturnedFlagCreateDate(null);
363                 } else {
364                     addClaimsReturnedItemHistory(itemData, user);
365                     getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(itemData.getItemIdentifier());
366                 }
367 
368                 if (itemData.isItemDamagedStatus()) {
369                     addItemDamagedHistory(itemData, user);
370                 }
371                 try {
372                     org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
373                     ItemOlemlRecordProcessor itemOlemlRecordProcessor1 = new ItemOlemlRecordProcessor();
374                     org.kuali.ole.docstore.common.document.content.instance.Item oleItem = itemOlemlRecordProcessor1.fromXML(item.getContent());
375                     String numberOfPiecesString = ((WorkInstanceOlemlForm) editorForm.getDocumentForm()).getSelectedItem().getNumberOfPieces();
376                     if(itemData.isMissingPieceFlag()){
377                         if(org.apache.commons.lang.StringUtils.isNotBlank(numberOfPiecesString)){
378                             if(Integer.parseInt(numberOfPiecesString) >= 1){
379                                 noOfPieces = Integer.parseInt(numberOfPiecesString);
380                             }else{
381                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, DocstoreResources.INVALID_NO_OF_PIECE);
382                                 return workInstanceOlemlForm;
383                             }
384 
385                         }else{
386                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, DocstoreResources.INVALID_NO_OF_PIECE);
387                             return workInstanceOlemlForm;
388                         }
389                     }
390 
391                     MissingPieceItemRecord missingPieceItemRecord = new MissingPieceItemRecord();
392                     List<MissingPieceItemRecord> missingPieceItemRecordList = new ArrayList<>();
393                     DateFormat parsedDate = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE);
394 
395                     if (itemData.isMissingPieceFlag() && !oleItem.isMissingPieceFlag()) {
396                         missingPieceItemRecord.setMissingPieceFlagNote(itemData.getMissingPieceFlagNote());
397                         missingPieceItemRecord.setMissingPieceCount(itemData.getMissingPiecesCount());
398                         missingPieceItemRecord.setMissingPieceDate(parsedDate.format(getDateTimeService().getCurrentDate()));
399                         missingPieceItemRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
400                         missingPieceItemRecord.setPatronBarcode(null);
401                         missingPieceItemRecord.setPatronId(itemData.getCurrentBorrower());
402                         missingPieceItemRecord.setItemId(itemData.getItemIdentifier());
403                        if(org.apache.commons.lang.StringUtils.isNotBlank(missingPieceItemRecord.getMissingPieceCount()) && (Integer.parseInt(missingPieceItemRecord.getMissingPieceCount()) >= 1)){
404                         if (noOfPieces >= Integer.parseInt(missingPieceItemRecord.getMissingPieceCount())) {
405                             if (!missingPieceItemRecord.getMissingPieceCount().isEmpty() ) {
406                                 if (itemData.getMissingPieceItemRecordList() != null && itemData.getMissingPieceItemRecordList().size() > 0) {
407                                     itemData.getMissingPieceItemRecordList().add(missingPieceItemRecord);
408                                 } else {
409                                     missingPieceItemRecordList.add(missingPieceItemRecord);
410                                     itemData.setMissingPieceItemRecordList(missingPieceItemRecordList);
411                                 }
412                             }
413                         } else {
414                             isExceedMaxCount = true;
415                         }
416                        }   else{
417                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, DocstoreResources.INVALID_MISSING_PIECE_COUNT);
418                            return workInstanceOlemlForm;
419                        }
420 
421 
422                     } else {
423                         if (itemData.isMissingPieceFlag() && oleItem.isMissingPieceFlag()) {
424                             Map<String, String> map = new HashMap<>();
425                             map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
426                             List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord> missingPieceItemRecordList1 =
427                                     (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord>) KRADServiceLocator.getBusinessObjectService()
428                                     .findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord.class, map, "missingPieceItemId", true);
429                             List<MissingPieceItemRecord> missingPieceItemRecords = new ArrayList<>();
430                             for (int index = 0; index < missingPieceItemRecordList1.size(); index++) {
431                                 MissingPieceItemRecord missingPieceItemRecord1 = new MissingPieceItemRecord();
432                                 if (index == missingPieceItemRecordList1.size() - 1) {
433                                     DateFormat dfs = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE);
434                                     String missingPieceItemDate = dfs.format(getDateTimeService().getCurrentDate());
435                                     missingPieceItemRecord1.setMissingPieceDate(missingPieceItemDate);
436                                     if(org.apache.commons.lang.StringUtils.isNotBlank(itemData.getMissingPiecesCount()) && (Integer.parseInt(itemData.getMissingPiecesCount()) >= 1 )){
437                                     if (noOfPieces > Integer.parseInt(itemData.getMissingPiecesCount()) ) {
438 
439                                         missingPieceItemRecord1.setMissingPieceCount(itemData.getMissingPiecesCount());
440                                     } else {
441                                         missingPieceItemRecord1.setMissingPieceCount(missingPieceItemRecordList1.get(index).getMissingPieceCount());
442                                         isExceedMaxCount = true;
443                                     }
444                                     }else{
445                                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, DocstoreResources.INVALID_MISSING_PIECE_COUNT);
446                                         return workInstanceOlemlForm;
447                                     }
448                                     missingPieceItemRecord1.setPatronBarcode(null);
449                                     missingPieceItemRecord1.setPatronId(itemData.getCurrentBorrower());
450                                     missingPieceItemRecord1.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
451                                     missingPieceItemRecord1.setItemId(itemData.getItemIdentifier());
452                                     missingPieceItemRecord1.setMissingPieceFlagNote(itemData.getMissingPieceFlagNote());
453                                         missingPieceItemRecords.add(missingPieceItemRecord1);
454 
455                                 } else {
456                                     if (missingPieceItemRecordList1.get(index).getMissingPieceDate() != null && !missingPieceItemRecordList1.get(index).getMissingPieceDate().toString().isEmpty()) {
457                                         SimpleDateFormat dateToSimpleDateFormat = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE);
458                                         Date missingPieceItemDate = null;
459                                         if(null != missingPieceItemRecordList1.get(index).getMissingPieceDate()){
460                                             try {
461                                                 missingPieceItemDate = new Date(missingPieceItemRecordList1.get(index).getMissingPieceDate().getTime());
462                                             } catch (org.kuali.ole.sys.exception.ParseException e) {
463                                                 LOG.error("format string to Date " + e);
464                                             }
465                                         }
466                                         missingPieceItemRecord1.setMissingPieceDate(dateToSimpleDateFormat.format(missingPieceItemDate));
467                                     }
468                                     missingPieceItemRecord1.setMissingPieceFlagNote(missingPieceItemRecordList1.get(index).getMissingPieceFlagNote());
469 
470 
471                                     missingPieceItemRecord1.setOperatorId(missingPieceItemRecordList1.get(index).getOperatorId());
472                                     missingPieceItemRecord1.setPatronBarcode(missingPieceItemRecordList1.get(index).getPatronBarcode());
473                                     missingPieceItemRecord1.setPatronId(missingPieceItemRecordList1.get(index).getPatronId());
474                                     missingPieceItemRecord1.setItemId(missingPieceItemRecordList1.get(index).getItemId());
475                                     missingPieceItemRecord1.setMissingPieceCount(missingPieceItemRecordList1.get(index).getMissingPieceCount());
476                                     if(org.apache.commons.lang.StringUtils.isNotBlank(missingPieceItemRecordList1.get(index).getMissingPieceCount()) && (Integer.parseInt(missingPieceItemRecordList1.get(index).getMissingPieceCount()) >= 1 )){
477                                     if (noOfPieces >= Integer.parseInt(missingPieceItemRecordList1.get(index).getMissingPieceCount())) {
478 
479                                             missingPieceItemRecords.add(missingPieceItemRecord1);
480 
481                                     } else {
482                                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,OLEConstants.EXCEED_MAX_COUNT);
483                                         return workInstanceOlemlForm;
484                                     }
485                                     }  else{
486                                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, DocstoreResources.INVALID_MISSING_PIECE_COUNT);
487                                         return workInstanceOlemlForm;
488                                     }
489 
490                                 }
491                             }
492                             itemData.setMissingPieceItemRecordList(missingPieceItemRecords);
493                         }
494                     }
495                 } catch (Exception e) {
496                     LOG.error("Exception ", e);
497                 }
498                 if (!isExceedMaxCount) {
499                     workInstanceOlemlForm.setViewId("WorkItemViewPage");
500                     if (!isValidItemData(workInstanceOlemlForm)) {
501 //                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
502                         return workInstanceOlemlForm;
503                     }
504 
505                     String itemId = editorForm.getDocId();
506                     itemData.setItemIdentifier(itemId);
507                     String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(itemData);
508 
509                     ItemOleml itemOleml = new ItemOleml();
510                     itemOleml.setContent(itemXmlContent);
511                     itemOleml.setId(itemId);
512                     itemOleml.setType(editorForm.getDocType());
513                     itemOleml.setFormat(editorForm.getDocFormat());
514                     itemOleml.setUpdatedBy(user);
515                     itemOleml.setUpdatedOn(dateStr);
516                     itemOleml.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
517                     itemOleml.setCategory(editorForm.getDocCategory());
518                     long startTime = System.currentTimeMillis();
519                     try {
520                         docstoreClient.updateItem(itemOleml);
521                     } catch (DocstoreException e) {
522                         LOG.error(e);
523                         DocstoreException docstoreException = (DocstoreException) e;
524                         if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
525                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
526                         } else {
527                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
528                         }
529 
530                         Holdings holdings = null;
531                         try {
532                             holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
533                         } catch (Exception e1) {
534                             LOG.error("Exception :", e1);
535                             docstoreException = (DocstoreException) e1;
536                             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
537                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
538                             } else {
539                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
540                             }
541                         }
542                         String docStoreData = holdings.getContent();
543                         OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
544                         workInstanceOlemlForm.setSelectedHolding(oleHoldings);
545 
546                         getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
547                         return workInstanceOlemlForm;
548                     } catch (Exception e) {
549                         LOG.error("Exception ", e);
550                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response", e.getMessage());
551                     }
552                     long endTime = System.currentTimeMillis();
553                     editorForm.setSolrTime(String.valueOf((endTime - startTime) / 1000));
554                     if (itemData.getLocation() != null) {
555                         String location = instanceEditorFormDataHandler.getLocationCode(itemData.getLocation().getLocationLevel());
556                         if (asrHelperService.isAnASRItem(location)) {
557 
558                             Map<String, String> asrItemMap = new HashMap<String, String>();
559                             asrItemMap.put("itemBarcode", itemData.getAccessInformation().getBarcode());
560                             List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
561                             if (asrItems.size() == 0) {
562                                 ASRItem asrItem = new ASRItem();
563                                 if (itemData.getAccessInformation() != null && itemData.getAccessInformation().getBarcode() != null) {
564                                     asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
565                                 }
566                                 if (bib.getTitle() != null) {
567                                     asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
568                                 }
569                                 if (bib.getAuthor() != null) {
570                                     asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
571                                 }
572                                 if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()) {
573                                     callNumber = (itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
574                                     prefix = itemData.getCallNumber().getPrefix() != null && !itemData.getCallNumber().getPrefix().isEmpty() ? itemData.getCallNumber().getPrefix() : "";
575                                     asrItem.setCallNumber(prefix + " " + callNumber);
576                                 } else if (workInstanceOlemlForm.getSelectedHolding() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()) {
577                                     callNumber = (workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
578                                     prefix = workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty() ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() : "";
579                                     asrItem.setCallNumber(prefix + " " + callNumber);
580                                 }
581                                 businessObjectService.save(asrItem);
582                             }
583                         }
584                     } else if (workInstanceOlemlForm.getSelectedHolding().getLocation() != null) {
585                         OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
586                         String location = oleHoldings.getLocation().getLocationLevel().getName();
587                         if (asrHelperService.isAnASRItem(location)) {
588                             Map<String, String> asrItemMap = new HashMap<String, String>();
589                             asrItemMap.put("itemBarcode", itemData.getAccessInformation().getBarcode());
590                             List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
591                             if (asrItems.size() == 0) {
592                                 ASRItem asrItem = new ASRItem();
593                                 if (itemData.getAccessInformation() != null && itemData.getAccessInformation().getBarcode() != null) {
594                                     asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
595                                 }
596                                 if (bib.getTitle() != null) {
597                                     asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
598                                 }
599                                 if (bib.getAuthor() != null) {
600                                     asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
601                                 }
602                                 if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()) {
603                                     callNumber = (itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
604                                     prefix = itemData.getCallNumber().getPrefix() != null && !itemData.getCallNumber().getPrefix().isEmpty() ? itemData.getCallNumber().getPrefix() : "";
605                                     asrItem.setCallNumber(prefix + " " + callNumber);
606                                 } else if (workInstanceOlemlForm.getSelectedHolding() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()) {
607                                     callNumber = (workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
608                                     prefix = workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty() ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() : "";
609                                     asrItem.setCallNumber(prefix + " " + callNumber);
610 
611                                 }
612                                 businessObjectService.save(asrItem);
613                             }
614                         }
615                     }
616                     String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
617                     String[] itemArray = null;
618                     if (itemProperty != null) {
619                         itemArray = itemProperty.split(",");
620                     }
621                     for (String status : itemArray) {
622                         if (status.equalsIgnoreCase("TRUE")) {
623                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
624                         } else if (status.equalsIgnoreCase("FALSE")) {
625                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
626                         }
627                     }
628                     String holdingId = workInstanceOlemlForm.getSelectedHolding().getHoldingsIdentifier();
629                     OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
630                     String holdingXmlContent = getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
631                     Holdings holdings = docstoreClient.retrieveHoldings(holdingId);
632                     holdings.setBib(bib);
633                     holdings.setContent(holdingXmlContent);
634                     holdings.setCategory(editorForm.getDocCategory());
635                     holdings.setType(DocType.HOLDINGS.getCode());
636                     holdings.setFormat(editorForm.getDocFormat());
637                     docstoreClient.updateHoldings(holdings);
638                     getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
639                     if (!isValidHoldingsData(workInstanceOlemlForm)) {
640                         getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
641                         return workInstanceOlemlForm;
642                     }
643                     editorMessage = "item.record.update.message";
644                 } else {
645                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,OLEConstants.EXCEED_MAX_COUNT);
646                     //editorMessage = ;
647                     return workInstanceOlemlForm;
648                 }
649 
650             } else {
651 
652                 if (!isValidItemData(workInstanceOlemlForm)) {
653 //                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
654                     return workInstanceOlemlForm;
655                 }
656                 String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
657                 Item oleItem = workInstanceOlemlForm.getSelectedItem();
658                 String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
659                 ItemOleml itemDoc = new ItemOleml();
660                 itemDoc.setCategory(DocCategory.WORK.getCode());
661                 itemDoc.setType(DocType.ITEM.getCode());
662                 itemDoc.setFormat(DocFormat.OLEML.getCode());
663                 itemDoc.setCreatedOn(dateStr);
664                 itemDoc.setCreatedBy(user);
665                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
666                 itemDoc.setContent(itemXmlContent);
667                 Holdings holdings = new PHoldings();
668                 holdings.setId(editorForm.getInstanceId());
669                 itemDoc.setHolding(holdings);
670                 long startTime = System.currentTimeMillis();
671                 try {
672                     docstoreClient.createItem(itemDoc);
673                 } catch (Exception e) {
674                     LOG.error("Exception :", e);
675                     DocstoreException docstoreException = (DocstoreException) e;
676                     String errorCode = docstoreException.getErrorCode();
677                     if (StringUtils.isNotEmpty(errorCode)) {
678                         Map<String, String> paramsMap = docstoreException.getErrorParams();
679                         if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
680                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
681                         } else {
682                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
683                         }
684                     } else {
685                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
686                     }
687 
688                     try {
689                         holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
690                     } catch (Exception e1) {
691                         LOG.error("Exception :", e1);
692                         docstoreException = (DocstoreException) e1;
693                         if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
694                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
695                         } else {
696                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
697                         }
698                     }
699                     String docStoreData = holdings.getContent();
700                     OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
701                     workInstanceOlemlForm.setSelectedHolding(oleHoldings);
702 
703                     getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
704                     return workInstanceOlemlForm;
705                 }
706                 long endtime = System.currentTimeMillis();
707                 editorForm.setSolrTime(String.valueOf((endtime - startTime) / 1000));
708                 if (oleItem.getLocation() != null) {
709                     String location = oleItem.getLocation().getLocationLevel().getName();
710                     if (asrHelperService.isAnASRItem(location)) {
711                         Map<String, String> asrItemMap = new HashMap<String, String>();
712                         asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
713                         List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
714                         if (asrItems.size() == 0) {
715                             ASRItem asrItem = new ASRItem();
716                             if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
717                                 asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
718                             }
719                             if (bib.getTitle() != null) {
720                                 asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
721                             }
722                             if (bib.getAuthor() != null) {
723                                 asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
724                             }
725                             if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()) {
726                                 callNumber = (oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
727                                 prefix = oleItem.getCallNumber().getPrefix() != null && !oleItem.getCallNumber().getPrefix().isEmpty() ? oleItem.getCallNumber().getPrefix() : "";
728                                 asrItem.setCallNumber(prefix + " " + callNumber);
729                             } else if (workInstanceOlemlForm.getSelectedHolding() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()) {
730                                 callNumber = (workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
731                                 prefix = workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty() ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() : "";
732                                 asrItem.setCallNumber(prefix + " " + callNumber);
733                             }
734                             businessObjectService.save(asrItem);
735                         }
736                     }
737                 } else if (workInstanceOlemlForm.getSelectedHolding().getLocation() != null) {
738                     OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
739                     String location = oleHoldings.getLocation().getLocationLevel().getName();
740                     if (asrHelperService.isAnASRItem(location)) {
741                         Map<String, String> asrItemMap = new HashMap<String, String>();
742                         asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
743                         List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
744                         if (asrItems.size() == 0) {
745                             ASRItem asrItem = new ASRItem();
746                             if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
747                                 asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
748                             }
749                             if (bib.getTitle() != null) {
750                                 asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
751                             }
752                             if (bib.getAuthor() != null) {
753                                 asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
754                             }
755                             if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()) {
756                                 callNumber = (oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
757                                 prefix = oleItem.getCallNumber().getPrefix() != null && !oleItem.getCallNumber().getPrefix().isEmpty() ? oleItem.getCallNumber().getPrefix() : "";
758                                 asrItem.setCallNumber(prefix + " " + callNumber);
759                             } else if (workInstanceOlemlForm.getSelectedHolding() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber() != null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()) {
760                                 callNumber = (workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
761                                 prefix = workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() != null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty() ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix() : "";
762                                 asrItem.setCallNumber(prefix + " " + callNumber);
763 
764                             }
765                             businessObjectService.save(asrItem);
766                         }
767                     }
768                 }
769                 editorForm.setDocId(itemDoc.getId());
770                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
771                 editorMessage = "item.record.load.message";
772             }
773         } catch (Exception e) {
774             LOG.error("Exception :", e);
775             DocstoreException docstoreException = (DocstoreException) e;
776             if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
777                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
778             } else {
779                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
780             }
781             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
782             return workInstanceOlemlForm;
783         }
784         org.kuali.ole.docstore.common.document.Item itemDocument = null;
785         try {
786             Holdings holdings = null;
787             try {
788                 holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
789             } catch (Exception e) {
790                 LOG.error("Exception :", e);
791                 DocstoreException docstoreException = (DocstoreException) e;
792                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
793                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
794                 } else {
795                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
796                 }
797             }
798             String docStoreData = holdings.getContent();
799             OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
800             workInstanceOlemlForm.setSelectedHolding(oleHoldings);
801             try {
802                 itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
803             } catch (DocstoreException e) {
804                 LOG.error(e);
805                 DocstoreException docstoreException = (DocstoreException) e;
806                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
807                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
808                 } else {
809                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
810                 }
811                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
812                 return workInstanceOlemlForm;
813             } catch (Exception e) {
814                 LOG.error("Exception ", e);
815                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response", e.getMessage());
816             }
817             Item item = itemOlemlRecordProcessor.fromXML(itemDocument.getContent());
818             editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(item.getItemIdentifier()));
819             editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
820             editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
821             editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
822             editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
823             workInstanceOlemlForm.setSelectedItem(item);
824             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
825             GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
826         } catch (Exception e) {
827             LOG.error("Exception :", e);
828             GlobalVariables.getMessageMap().clearErrorMessages();
829             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.submit.fail.message");
830         }
831         if (StringUtils.isNotBlank(workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier())) {
832             Map poMap = new HashMap();
833             poMap.put(OLEConstants.PURAP_DOC_IDENTIFIER, workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier());
834             OlePurchaseOrderDocument olePurchaseOrderDocument = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, poMap);
835             if (olePurchaseOrderDocument != null) {
836                 String poId = olePurchaseOrderDocument.getDocumentNumber();
837                 Map<String, String> map = new HashMap<>();
838                 map.put(org.kuali.ole.sys.OLEConstants.OleCopy.PO_DOC_NUM, poId);
839                 KRADServiceLocator.getBusinessObjectService().deleteMatching(OLELinkPurapDonor.class, map);
840                 if (workInstanceOlemlForm.getSelectedItem().getDonorInfo().size() > 0) {
841                     for (DonorInfo donorInfo : workInstanceOlemlForm.getSelectedItem().getDonorInfo()) {
842                         if (donorInfo.getDonorCode() != null && !donorInfo.getDonorCode().isEmpty()) {
843                             map.clear();
844                             map.put(OLEConstants.DONOR_CODE, donorInfo.getDonorCode());
845                             OLELinkPurapDonor newOleLinkPurapDonor = new OLELinkPurapDonor();
846                             List<OLEDonor> oleDonors = (List<OLEDonor>) KRADServiceLocator.getBusinessObjectService().findMatching(OLEDonor.class, map);
847                             map.clear();
848                             if (StringUtils.isNotBlank(workInstanceOlemlForm.getSelectedItem().getItemIdentifier())) {
849                                 map.put(OLEConstants.OleDeliverRequest.ITEM_UUID, workInstanceOlemlForm.getSelectedItem().getItemIdentifier());
850                             }
851                             map.put(org.kuali.ole.sys.OLEConstants.OleCopy.PO_DOC_NUM, poId);
852                             List<OleCopy> oleCopy = (List<OleCopy>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCopy.class, map);
853                             if (oleCopy != null && oleCopy.size() > 0) {
854                                 newOleLinkPurapDonor.setCorrectionItemId(oleCopy.get(0).getCorrectionItemId());
855                                 newOleLinkPurapDonor.setReqItemId(oleCopy.get(0).getReqItemId());
856                                 newOleLinkPurapDonor.setPoDocNum(oleCopy.get(0).getPoDocNum());
857                                 newOleLinkPurapDonor.setReceivingItemId(oleCopy.get(0).getReceivingItemId());
858                                 newOleLinkPurapDonor.setDonorId(oleDonors.get(0).getDonorId());
859                                 newOleLinkPurapDonor.setDonorCode(donorInfo.getDonorCode());
860                                 newOleLinkPurapDonor.setPoItemId(oleCopy.get(0).getPoItemId());
861                                 KRADServiceLocator.getBusinessObjectService().save(newOleLinkPurapDonor);
862                             }
863                             map.clear();
864                         }
865                     }
866                 }
867             }
868         }
869         // To remove existing item from bib tree
870         removeDocumentFromTree(editorForm);
871         // To add new item or updated item in bib tree
872         addItemToBibTree(workInstanceOlemlForm.getBibTreeList(), itemDocument);
873         return workInstanceOlemlForm;
874     }
875 
876     private void addItemDamagedHistory(Item itemData, String user) throws Exception {
877         DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
878         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
879         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
880         Item oleItem = itemOlemlRecordProcessor.fromXML(item.getContent());
881         ItemDamagedRecord itemDamagedRecord = new ItemDamagedRecord();
882         List<ItemDamagedRecord> itemDamagedRecords = new ArrayList<>();
883         if(!oleItem.isItemDamagedStatus()){
884             itemDamagedRecord.setDamagedItemNote(itemData.getDamagedItemNote());
885             itemDamagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
886             itemDamagedRecord.setPatronBarcode(null);
887             itemDamagedRecord.setDamagedPatronId(itemData.getCurrentBorrower());
888             itemDamagedRecord.setOperatorId(user);
889             itemDamagedRecord.setItemId(itemData.getItemIdentifier());
890             if(itemData.getItemDamagedRecords() != null && itemData.getItemDamagedRecords().size() > 0){
891                 itemData.getItemDamagedRecords().add(itemDamagedRecord);
892             } else {
893                 itemDamagedRecords.add(itemDamagedRecord);
894                 itemData.setItemDamagedRecords(itemDamagedRecords);
895             }
896         } else {
897             Map<String,String> map = new HashMap<>();
898             map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
899             List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord> itemDamagedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord>) KRADServiceLocator.getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord.class, map, "itemDamagedId", true);
900             List<ItemDamagedRecord> damagedRecordList = new ArrayList<>();
901             if(CollectionUtils.isNotEmpty(itemDamagedRecordList)){
902                 for(int index=0 ; index < itemDamagedRecordList.size() ; index++){
903                     ItemDamagedRecord damagedRecord = new ItemDamagedRecord();
904                     if(index == itemDamagedRecordList.size()-1){
905                         damagedRecord.setDamagedItemNote(itemData.getDamagedItemNote());
906                         damagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
907                         damagedRecord.setPatronBarcode(null);
908                         damagedRecord.setDamagedPatronId(itemData.getCurrentBorrower());
909                         damagedRecord.setOperatorId(user);
910                         damagedRecord.setItemId(itemData.getItemIdentifier());
911                     } else {
912                         if (itemDamagedRecordList.get(index).getDamagedItemDate() != null && !itemDamagedRecordList.get(index).getDamagedItemDate().toString().isEmpty()) {
913                             SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
914                             SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
915                             Date itemDamagedDate = null;
916                             try {
917                                 itemDamagedDate = format2.parse(itemDamagedRecordList.get(index).getDamagedItemDate().toString());
918                             } catch (ParseException e) {
919                                 LOG.error("format string to Date " + e);
920                             }
921                             damagedRecord.setDamagedItemDate(format1.format(itemDamagedDate).toString());
922                         }
923                         damagedRecord.setDamagedItemNote(itemDamagedRecordList.get(index).getDamagedItemNote());
924                         damagedRecord.setPatronBarcode(itemDamagedRecordList.get(index).getPatronBarcode());
925                         damagedRecord.setDamagedPatronId(itemDamagedRecordList.get(index).getDamagedPatronId());
926                         damagedRecord.setOperatorId(itemDamagedRecordList.get(index).getOperatorId());
927                         damagedRecord.setItemId(itemDamagedRecordList.get(index).getItemId());
928                     }
929                     damagedRecordList.add(damagedRecord);
930                 }
931                 itemData.setItemDamagedRecords(damagedRecordList);
932             }
933         }
934     }
935 
936     private void addClaimsReturnedItemHistory(Item itemData, String user) throws Exception {
937         DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
938         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
939         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
940         Item oleItem = itemOlemlRecordProcessor.fromXML(item.getContent());
941         ItemClaimsReturnedRecord itemClaimsReturnedRecord = new ItemClaimsReturnedRecord();
942         List<ItemClaimsReturnedRecord> itemClaimsReturnedRecords = new ArrayList<>();
943         if(!oleItem.isClaimsReturnedFlag()){
944             itemClaimsReturnedRecord.setClaimsReturnedNote(itemData.getClaimsReturnedNote());
945             if (itemData.getClaimsReturnedFlagCreateDate() != null && !itemData.getClaimsReturnedFlagCreateDate().isEmpty()) {
946                 itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(itemData.getClaimsReturnedFlagCreateDate());
947             }
948             else{
949                 itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
950             }
951             itemClaimsReturnedRecord.setClaimsReturnedOperatorId(user);
952             itemClaimsReturnedRecord.setItemId(itemData.getItemIdentifier());
953             itemClaimsReturnedRecord.setClaimsReturnedPatronBarcode(null);
954             itemClaimsReturnedRecord.setClaimsReturnedPatronId(itemData.getCurrentBorrower());
955             if(itemData.getItemClaimsReturnedRecords() != null && itemData.getItemClaimsReturnedRecords().size() > 0){
956                 itemData.getItemClaimsReturnedRecords().add(itemClaimsReturnedRecord);
957             }
958             else{
959                 itemClaimsReturnedRecords.add(itemClaimsReturnedRecord);
960                 itemData.setItemClaimsReturnedRecords(itemClaimsReturnedRecords);
961             }
962         } else{
963             Map<String,String> map = new HashMap<>();
964             map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
965             List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord> claimsReturnedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord>) KRADServiceLocator.getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord.class, map, "claimsReturnedId", true);
966             List<ItemClaimsReturnedRecord> itemClaimsReturnedRecordList = new ArrayList<>();
967             if(CollectionUtils.isNotEmpty(claimsReturnedRecordList)){
968                 for(int index=0 ; index < claimsReturnedRecordList.size() ; index++){
969                     ItemClaimsReturnedRecord claimsReturnedRecord = new ItemClaimsReturnedRecord();
970                     if(index == claimsReturnedRecordList.size()-1){
971                         if (itemData.getClaimsReturnedFlagCreateDate() != null && !itemData.getClaimsReturnedFlagCreateDate().isEmpty()) {
972                             claimsReturnedRecord.setClaimsReturnedFlagCreateDate(itemData.getClaimsReturnedFlagCreateDate());
973                         }
974                         else{
975                             claimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
976                         }
977                         claimsReturnedRecord.setClaimsReturnedNote(itemData.getClaimsReturnedNote());
978                         claimsReturnedRecord.setClaimsReturnedPatronBarcode(null);
979                         claimsReturnedRecord.setClaimsReturnedPatronId(itemData.getCurrentBorrower());
980                         claimsReturnedRecord.setClaimsReturnedOperatorId(user);
981                         claimsReturnedRecord.setItemId(itemData.getItemIdentifier());
982                     } else {
983                         if (claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString() != null) {
984                             SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
985                             SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
986                             Date claimsReturnedDate = null;
987                             try {
988                                 claimsReturnedDate = format2.parse(claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString());
989                             } catch (ParseException e) {
990                                 LOG.error("format string to Date " + e);
991                             }
992                             claimsReturnedRecord.setClaimsReturnedFlagCreateDate(format1.format(claimsReturnedDate).toString());
993                         }
994                         claimsReturnedRecord.setClaimsReturnedNote(claimsReturnedRecordList.get(index).getClaimsReturnedNote());
995                         claimsReturnedRecord.setClaimsReturnedPatronBarcode(claimsReturnedRecordList.get(index).getClaimsReturnedPatronBarcode());
996                         claimsReturnedRecord.setClaimsReturnedPatronId(claimsReturnedRecordList.get(index).getClaimsReturnedPatronId());
997                         claimsReturnedRecord.setClaimsReturnedOperatorId(claimsReturnedRecordList.get(index).getClaimsReturnedOperatorId());
998                         claimsReturnedRecord.setItemId(claimsReturnedRecordList.get(index).getItemId());
999                     }
1000                     itemClaimsReturnedRecordList.add(claimsReturnedRecord);
1001                 }
1002                 itemData.setItemClaimsReturnedRecords(itemClaimsReturnedRecordList);
1003             }
1004         }
1005     }
1006 
1007     /**
1008      * This methods adds the new item or updated item to the bib tree to build left pane tree.
1009      * @param bibTreeList
1010      * @param selectedItemDocument
1011      */
1012     private void addItemToBibTree(List<BibTree> bibTreeList, org.kuali.ole.docstore.common.document.Item selectedItemDocument) {
1013         if (CollectionUtils.isNotEmpty(bibTreeList)) {
1014             for (BibTree bibTree : bibTreeList) {
1015                 if (CollectionUtils.isNotEmpty(bibTree.getHoldingsTrees())) {
1016                     for (HoldingsTree holdingsTree : bibTree.getHoldingsTrees()) {
1017                         if (null != holdingsTree.getHoldings() && null != selectedItemDocument.getHolding()) {
1018                             String holdingsId = holdingsTree.getHoldings().getId();
1019                             String selectedItemHoldingsId = selectedItemDocument.getHolding().getId();
1020                             if (null != holdingsId && null != selectedItemHoldingsId) {
1021                                 if (holdingsId.equals(selectedItemHoldingsId)) {
1022                                     holdingsTree.setHoldings(selectedItemDocument.getHolding());
1023                                     holdingsTree.getItems().add(selectedItemDocument);
1024                                 }
1025                             }
1026                         }
1027                     }
1028                 }
1029             }
1030         }
1031     }
1032 
1033     @Override
1034     public EditorForm createNewRecord(EditorForm editorForm, BibTree bibTree) {
1035 
1036         if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
1037             editorForm.setNeedToCreateInstance(true);
1038         }
1039         editNewRecord(editorForm, bibTree);
1040         return editorForm.getDocumentForm();
1041     }
1042 
1043     @Override
1044     public EditorForm editNewRecord(EditorForm editorForm, BibTree bibTree) {
1045         WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
1046         if ((editorForm.getDocumentForm() instanceof WorkInstanceOlemlForm)) {
1047             workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1048             workInstanceOlemlForm.setViewId(editorForm.getDocumentForm().getViewId());
1049         }
1050 
1051         workInstanceOlemlForm.setDocCategory("work");
1052         workInstanceOlemlForm.setDocType("item");
1053         workInstanceOlemlForm.setDocFormat("oleml");
1054 
1055         if (bibTree != null && bibTree.getHoldingsTrees() != null) {
1056             HoldingsTree holdingsTree = bibTree.getHoldingsTrees().get(0);
1057             if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
1058 //                editorForm.setHeaderText("Import Bib Step-4 Instance Editor (Item)- OLEML Format");
1059                 editorForm.setHeaderText("Import Bib Step-4 Item");
1060                 // validate user entered holding data before going to item tab
1061                 if (!isValidHoldingsData(workInstanceOlemlForm)) {
1062                     return workInstanceOlemlForm;
1063                 }
1064                 holdingsTree.getHoldings().setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1065                 holdingsTree.getHoldings().setCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
1066                 Item item = itemOlemlRecordProcessor.fromXML(holdingsTree.getItems().get(0).getContent());
1067                 List<Note> notes = ensureAtleastOneNote(item.getNote());
1068                 item.setNote(notes);
1069                 workInstanceOlemlForm.setSelectedItem(item);
1070                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
1071                 //workInstanceOlemlForm.setMessage("Please enter details for new Item record.");
1072                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
1073                         "item.details.new.message");
1074             } else if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkItemViewPage")) {
1075                 if (!isValidItemData(workInstanceOlemlForm)) {
1076                     return workInstanceOlemlForm;
1077                 }
1078                 Item item = workInstanceOlemlForm.getSelectedItem();
1079                 Map<String, String> mapObject = new HashMap<String, String>();
1080                 String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
1081                 try {
1082                     String holdingXmlContent = getInstanceEditorFormDataHandler()
1083                             .buildHoldingContent(workInstanceOlemlForm.getSelectedHolding());
1084                     holdingsTree.getHoldings().setContent(holdingXmlContent);
1085 
1086                     String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(item, staffOnlyFlagForItem);
1087                     holdingsTree.getItems().get(0).setContent(itemXmlContent);
1088 
1089                 } catch (Exception e) {
1090                     LOG.error("Exception :", e);
1091                     StringBuffer instanceEditorErrorMessage = new StringBuffer(
1092                             OLEConstants.INSTANCE_EDITOR_FAILURE).append(" :: \n" + e.getMessage());
1093                     workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
1094                     LOG.error(instanceEditorErrorMessage);
1095                 }
1096             }
1097         }
1098         editorForm.setDocumentForm(workInstanceOlemlForm);
1099         return editorForm;
1100     }
1101 
1102     @Override
1103     public String saveDocument(BibTree bibTree, EditorForm editorForm) {
1104         String responseFromDocstore = "success";
1105         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1106         if (bibTree != null) {
1107             try {
1108                 docstoreClient.createBibTree(bibTree);
1109             } catch (DocstoreException e) {
1110                 LOG.error(e);
1111                 DocstoreException docstoreException = (DocstoreException) e;
1112                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1113                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1114                 } else {
1115                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1116                 }
1117             } catch (Exception e) {
1118                 LOG.error("Exception ", e);
1119                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
1120             }
1121         }
1122         editorForm.setDocumentForm(workInstanceOlemlForm);
1123         return responseFromDocstore;
1124     }
1125 
1126 
1127     /**
1128      * Gets the InstanceEditorFormDataHandler attribute.
1129      *
1130      * @return Returns InstanceEditorFormDataHandler.
1131      */
1132     private InstanceEditorFormDataHandler getInstanceEditorFormDataHandler() {
1133         if (null == instanceEditorFormDataHandler) {
1134             instanceEditorFormDataHandler = new InstanceEditorFormDataHandler();
1135         }
1136         return instanceEditorFormDataHandler;
1137     }
1138 
1139     private List<Note> ensureAtleastOneNote(List<Note> notes) {
1140         if (notes == null) {
1141             notes = new ArrayList<Note>();
1142         }
1143         if (notes.size() == 0) {
1144             Note note = new Note();
1145             notes.add(note);
1146         }
1147         return notes;
1148     }
1149 
1150     private List<DonorInfo> ensureAtleastOneDonor(List<DonorInfo> donorInfos) {
1151         if (donorInfos == null) {
1152             donorInfos = new ArrayList<DonorInfo>();
1153         }
1154         if (donorInfos.size() == 0) {
1155             DonorInfo donorInfo = new DonorInfo();
1156             donorInfos.add(donorInfo);
1157         }else{
1158             for(DonorInfo donorInfo : donorInfos){
1159                 if (donorInfo != null && StringUtils.isNotEmpty(donorInfo.getDonorCode())) {
1160                     Map map = new HashMap();
1161                     map.put("donorCode", donorInfo.getDonorCode());
1162                     OLEDonor oleDonor = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEDonor.class, map);
1163                     if (oleDonor != null) {
1164                         donorInfo.setDonorPublicDisplay(oleDonor.getDonorPublicDisplay());
1165                         donorInfo.setDonorNote(oleDonor.getDonorNote());
1166                     }
1167                 }
1168                 //donorInfo.
1169             }
1170         }
1171         return donorInfos;
1172     }
1173 
1174     private boolean canCreateItem(String principalId) {
1175         PermissionService service = KimApiServiceLocator.getPermissionService();
1176         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_ADD_ITEM);
1177     }
1178 
1179     private boolean canEditItem(String principalId) {
1180         PermissionService service = KimApiServiceLocator.getPermissionService();
1181         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_EDIT_ITEM);
1182     }
1183 
1184     private void addItemInformation(EditorForm editorForm) {
1185         //TODO: do as per tree structure
1186     }
1187 
1188     /**
1189      * Validates the item data and returns true if it is valid
1190      *
1191      * @param workInstanceOlemlForm
1192      * @return
1193      */
1194     private boolean isValidItemData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1195         Item item = workInstanceOlemlForm.getSelectedItem();
1196         boolean isValidItem = true;
1197 //        StringBuffer stringBuffer = new StringBuffer();
1198         String oldItemStatus = workInstanceOlemlForm.getOldItemStatus();
1199         String itemStatus = item.getItemStatus().getCodeValue();
1200         String itemProperty = getInstanceEditorFormDataHandler()
1201                 .getParameter(OLEConstants.DESC_NMSPC, OLEConstants.DESCRIBE_COMPONENT, OLEParameterConstants.ITEM_STATUS_READONLY);
1202         String[] itemArray = itemProperty.split(",");
1203         //If current item status is changed when compared with previous status
1204         if ((org.apache.commons.lang.StringUtils.isNotEmpty(itemStatus)) && (!itemStatus.equals(oldItemStatus))) {
1205             for (String status : itemArray) {
1206                 if (status.equalsIgnoreCase(itemStatus)) {
1207 //                    stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_INVALID + "</font>");
1208                     //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1209                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "invalid.item.status");
1210                     return false;
1211                 }
1212             }
1213         }
1214         String location = "";
1215         String holdingsLocation = "";
1216         if (item.getLocation() != null) {
1217             location = item.getLocation().getLocationLevel().getName();
1218         }
1219         OleHoldings holdings = workInstanceOlemlForm.getSelectedHolding();
1220         if (holdings.getLocation() != null) {
1221             holdingsLocation = holdings.getLocation().getLocationLevel().getName();
1222         }
1223 
1224 
1225         //Display error message when item status is empty
1226         if ( workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
1227                 (item.getItemStatus() == null || item.getItemStatus().getCodeValue() == "" ||
1228                         item.getItemStatus().getCodeValue().length() < 0)) {
1229             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_ERRORMESSAGE + "</font>");
1230             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus.codeValue", "error.item.status.required");
1231             workInstanceOlemlForm.setValidInput(false);
1232             isValidItem = false;
1233         }
1234 
1235         //Display error message when item type is empty
1236         if (workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
1237                 (item.getItemType() == null || item.getItemType().getCodeValue() == null || item.getItemType().getCodeValue()=="" || item.getItemType().getCodeValue().length()==0 ||   item.getItemType().getCodeValue().length() < 0)) {
1238 //            stringBuffer.append("<br>");
1239             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERRORMESSAGE + "</font>");
1240             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemType.codeValue", "error.item.type.required");
1241             workInstanceOlemlForm.setValidInput(false);
1242             isValidItem = false;
1243         }
1244 
1245         if (holdingsLocation != null && holdingsLocation.length() != 0 && !isValidLocation(holdingsLocation)) {
1246 //            stringBuffer.append("<br>");
1247             GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1248             workInstanceOlemlForm.setValidInput(false);
1249             isValidItem = false;
1250         }
1251         //Display error message when location is invalid
1252         if (location != null && location.length() != 0 && !isValidLocation(location)) {
1253 //            stringBuffer.append("<br>");
1254             //stringBuffer.append("<font size='3' color='red'>Please enter the valid location.</font>");
1255             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.location.locationLevel.name", "error.location");
1256             workInstanceOlemlForm.setValidInput(false);
1257             isValidItem = false;
1258         }
1259 
1260         boolean hasPermission = canUpdateItemStatus(GlobalVariables.getUserSession().getPrincipalId());
1261         if (hasPermission) {
1262 //            if (org.apache.commons.lang.StringUtils.isEmpty(stringBuffer.toString())) {
1263 //                isValidItem = true;
1264 //            } else {
1265 //                isValidItem = false;
1266 //            }
1267         } else {
1268             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERROR_MESSAGE + "</font>");
1269             //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1270             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.type.authorization");
1271             return false;
1272         }
1273         return isValidItem;
1274     }
1275 
1276     private boolean isValidLocation(String location) {
1277 
1278         List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
1279         if (locationList != null && locationList.size() > 0) {
1280             for (String locationValue : locationList) {
1281                 if (locationValue.equalsIgnoreCase(location)) {
1282                     return true;
1283                 }
1284             }
1285         }
1286         return false;
1287     }
1288 
1289     private boolean canUpdateItemStatus(String principalId) {
1290         LOG.debug("Inside the canUpdateItemStatus method");
1291         PermissionService service = KimApiServiceLocator.getPermissionService();
1292         return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_UPDATE_IEM_STATUS);
1293     }
1294 
1295     /**
1296      * Validates the Holdings data and returns true if it is valid
1297      *
1298      * @param workInstanceOlemlForm
1299      * @return
1300      */
1301     private boolean isValidHoldingsData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1302         OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
1303         String location = null;
1304         if (oleHoldings != null && oleHoldings.getLocation() != null && oleHoldings.getLocation().getLocationLevel() != null) {
1305             location = oleHoldings.getLocation().getLocationLevel().getName();
1306         }
1307         if (location != null && location.length() != 0 && !isValidLocation(location)) {
1308             //workInstanceOlemlForm.setMessage("<font size='3' color='red'>Please enter valid location.</font>");
1309             GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1310             workInstanceOlemlForm.setValidInput(false);
1311             return false;
1312         }
1313         return true;
1314     }
1315 
1316 
1317     public EditorForm deleteVerify(EditorForm editorForm) {
1318         //LOG.info("in instance editor class");
1319         String docId = editorForm.getDocId();
1320         String operation = "deleteVerify";
1321         //        String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1322         //        LOG.info("deleteVerify responseXml-->" + responseXml);
1323         //        editorForm.setDeleteVerifyResponse(responseXml);
1324         editorForm.setShowDeleteTree(true);
1325         editorForm.setHasLink(true);
1326         //        Node<DocumentTreeNode, String> docTree = buildDocSelectionTree(responseXml);
1327         List<String> uuidList = new ArrayList<>(0);
1328         uuidList.add(editorForm.getDocId());
1329         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1330         Node<DocumentTreeNode, String> docTree = null;
1331         try {
1332             docTree = documentSelectionTree.add(uuidList, editorForm.getDocType());
1333         } catch (SolrServerException e) {
1334             LOG.error("Exception :", e);
1335             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
1336         }
1337         editorForm.getDocTree().setRootElement(docTree);
1338         StringBuffer deleteMessage = new StringBuffer();
1339         if(StringUtils.isEmpty(deleteMessage)){
1340             deleteMessage.append("The following item record will be deleted.");
1341         }
1342         editorForm.setDeleteMessage(deleteMessage.toString());
1343         editorForm.setViewId("DeleteViewPage");
1344         return editorForm;
1345 
1346     }
1347 
1348     /**
1349      * This method deletes the item record from docstore by the doc id.
1350      * @param editorForm
1351      * @return
1352      * @throws Exception
1353      */
1354     public EditorForm delete(EditorForm editorForm) throws Exception {
1355         return deleteFromDocStore(editorForm);
1356     }
1357 
1358     @Override
1359     public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1360         String methodName = request.getParameter("methodToCall");
1361         if (methodName.equalsIgnoreCase("addItemNote")) {
1362             WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1363             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1364             index++;
1365             List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1366             itemNote.add(index, new Note());
1367             editorForm.setDocumentForm(workInstanceOlemlForm);
1368         } else if (methodName.equalsIgnoreCase("removeItemNote")) {
1369             WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1370             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1371             List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1372             if (itemNote.size() > 1) {
1373                 itemNote.remove(index);
1374             } else {
1375                 if (itemNote.size() == 1) {
1376                     itemNote.remove(index);
1377                     Note note = new Note();
1378                     itemNote.add(note);
1379                 }
1380             }
1381             editorForm.setDocumentForm(workInstanceOlemlForm);
1382         }
1383         return editorForm;
1384     }
1385 
1386     @Override
1387     public EditorForm addORRemoveItemDonor(EditorForm editorForm, HttpServletRequest request) {
1388         String methodName = request.getParameter("methodToCall");
1389         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1390         int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1391         if (methodName.equalsIgnoreCase("addDonorToItem")) {
1392             index++;
1393             List<DonorInfo> donorInfo = workInstanceOlemlForm.getSelectedItem().getDonorInfo();
1394             donorInfo.add(index, new DonorInfo());
1395             editorForm.setDocumentForm(workInstanceOlemlForm);
1396         } else if (methodName.equalsIgnoreCase("removeDonorFromItem")) {
1397             List<DonorInfo> donorInfo = workInstanceOlemlForm.getSelectedItem().getDonorInfo();
1398             if(donorInfo.size() > 1){
1399                 donorInfo.remove(index);
1400             }else{
1401                 if(donorInfo.size() ==1){
1402                     donorInfo.remove(index);
1403                     DonorInfo donor = new DonorInfo();
1404                     donorInfo.add(donor);
1405                 }
1406             }
1407             editorForm.setDocumentForm(workInstanceOlemlForm);
1408         }
1409         return editorForm;
1410     }
1411 
1412     @Override
1413     public EditorForm bulkUpdate(EditorForm editorForm, List<String> ids) {
1414         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1415         Date date = new Date();
1416         SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE+" HH:mm:ss");
1417         String dateStr = sdf.format(date);
1418         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
1419         String docId = editorForm.getDocId();
1420         String instanceId = editorForm.getInstanceId();
1421         String editorMessage = "";
1422         Bib bib = null;
1423         editorForm.setHeaderText("Global Edit - Item");
1424 
1425         try {
1426 
1427             workInstanceOlemlForm.setGlobalEditFlag("true");
1428             if (!isValidItemData(workInstanceOlemlForm)) {
1429                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1430                 return workInstanceOlemlForm;
1431             }
1432             String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
1433             Item oleItem = workInstanceOlemlForm.getSelectedItem();
1434             String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
1435             ItemOleml itemDoc = new ItemOleml();
1436             itemDoc.setCategory(DocCategory.WORK.getCode());
1437             itemDoc.setType(DocType.ITEM.getCode());
1438             itemDoc.setFormat(DocFormat.OLEML.getCode());
1439             itemDoc.setCreatedOn(dateStr);
1440             itemDoc.setCreatedBy(user);
1441             String canUpdateStaffOnlyFlag = "false";
1442             if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("Y")) {
1443                 canUpdateStaffOnlyFlag = "true";
1444                 editorForm.setStaffOnlyFlagForItem(true);
1445                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1446             }
1447             else if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("N")) {
1448                 canUpdateStaffOnlyFlag = "true";
1449                 editorForm.setStaffOnlyFlagForItem(false);
1450                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1451             }
1452             itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
1453             itemDoc.setContent(itemXmlContent);
1454             /*Holdings holdings = new PHoldings();
1455             holdings.setId(editorForm.getInstanceId());
1456             itemDoc.setHolding(holdings);*/
1457             try {
1458                 getDocstoreClientLocator().getDocstoreClient().bulkUpdateItem(itemDoc,ids,canUpdateStaffOnlyFlag);
1459             } catch (Exception e) {
1460                 LOG.error("Exception :", e);
1461                 DocstoreException docstoreException = (DocstoreException) e;
1462                 String errorCode = docstoreException.getErrorCode();
1463                 if (StringUtils.isNotEmpty(errorCode)) {
1464                     Map<String, String> paramsMap = docstoreException.getErrorParams();
1465                     if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
1466                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
1467                     } else {
1468                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
1469                     }
1470                 } else {
1471                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1472                 }
1473                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1474                 return workInstanceOlemlForm;
1475             }
1476             editorForm.setDocId(itemDoc.getId());
1477             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1478             editorMessage = "item.record.load.message";
1479 
1480         } catch (Exception e) {
1481             LOG.error("Exception :", e);
1482             DocstoreException docstoreException = (DocstoreException) e;
1483             if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1484                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1485             } else {
1486                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1487             }
1488             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1489             return workInstanceOlemlForm;
1490         }
1491         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
1492         return workInstanceOlemlForm;
1493     }
1494 
1495     @Override
1496     public EditorForm copy(EditorForm editorForm) {
1497         editorForm.setDocId(null);
1498         editorForm.setOleLoanIntransitRecordHistories(Collections.EMPTY_LIST);
1499 
1500         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1501         Item selectedItem = workInstanceOlemlForm.getSelectedItem();
1502         if (null != selectedItem) {
1503             AccessInformation accessInformation = selectedItem.getAccessInformation();
1504             if (null != accessInformation) {
1505                 accessInformation.setBarcode(null);
1506             }
1507             selectedItem.setEnumeration(null);
1508             selectedItem.setPurchaseOrderLineItemIdentifier(null);
1509             selectedItem.setVendorLineItemIdentifier(null);
1510             selectedItem.setFund(null);
1511             selectedItem.setPrice(null);
1512 
1513             selectedItem.setCurrentBorrower(null);
1514             selectedItem.setProxyBorrower(null);
1515             selectedItem.setItemStatusEffectiveDate(null);
1516             selectedItem.setFastAddFlag(false);
1517             selectedItem.setDueDateTime(null);
1518             selectedItem.setClaimsReturnedFlag(false);
1519             selectedItem.setClaimsReturnedFlagCreateDate(null);
1520             selectedItem.setClaimsReturnedNote(null);
1521             selectedItem.setItemDamagedStatus(false);
1522             selectedItem.setDamagedItemNote(null);
1523             selectedItem.setMissingPieceFlag(false);
1524             selectedItem.setMissingPiecesCount(null);
1525             selectedItem.setMissingPieceFlagNote(null);
1526             selectedItem.getNote().clear();
1527             selectedItem.getNote().add(new Note());
1528         }
1529         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, OLEConstants.MARC_EDITOR_ITEM_COPY_MESSAGE);
1530         return editorForm;
1531     }
1532 
1533     public DateTimeService getDateTimeService() {
1534         return (DateTimeService)SpringContext.getService("dateTimeService");
1535     }
1536 }