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.OleDeliverRequestBo;
13  import org.kuali.ole.deliver.bo.OleLoanDocument;
14  import org.kuali.ole.deliver.calendar.service.DateUtil;
15  import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
16  import org.kuali.ole.describe.bo.DocumentSelectionTree;
17  import org.kuali.ole.describe.bo.DocumentTreeNode;
18  import org.kuali.ole.describe.bo.InstanceEditorFormDataHandler;
19  import org.kuali.ole.describe.form.EditorForm;
20  import org.kuali.ole.describe.form.WorkBibMarcForm;
21  import org.kuali.ole.describe.form.WorkInstanceOlemlForm;
22  import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
23  import org.kuali.ole.docstore.common.client.DocstoreClient;
24  import org.kuali.ole.docstore.common.document.*;
25  import org.kuali.ole.docstore.common.document.HoldingsTree;
26  import org.kuali.ole.docstore.common.document.content.enums.DocCategory;
27  import org.kuali.ole.docstore.common.document.content.enums.DocFormat;
28  import org.kuali.ole.docstore.common.document.content.enums.DocType;
29  import org.kuali.ole.docstore.common.document.content.instance.*;
30  import org.kuali.ole.docstore.common.document.content.instance.Item;
31  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
32  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
33  import org.kuali.ole.docstore.common.exception.DocstoreException;
34  import org.kuali.ole.docstore.engine.client.DocstoreLocalClient;
35  import org.kuali.ole.select.bo.OLEDonor;
36  import org.kuali.ole.select.bo.OLELinkPurapDonor;
37  import org.kuali.ole.select.businessobject.OleCopy;
38  import org.kuali.rice.core.api.util.tree.Node;
39  import org.kuali.rice.kim.api.permission.PermissionService;
40  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
41  import org.kuali.rice.krad.service.BusinessObjectService;
42  import org.kuali.rice.krad.service.KRADServiceLocator;
43  import org.kuali.rice.krad.uif.UifParameters;
44  import org.kuali.rice.krad.util.GlobalVariables;
45  import org.kuali.rice.krad.util.KRADConstants;
46  
47  import javax.servlet.http.HttpServletRequest;
48  import java.text.Format;
49  import java.text.ParseException;
50  import java.text.SimpleDateFormat;
51  import java.util.*;
52  
53  /**
54   * Created with IntelliJ IDEA.
55   * User: sambasivam
56   * Date: 1/9/14
57   * Time: 5:01 PM
58   * To change this template use File | Settings | File Templates.
59   */
60  public class WorkItemOlemlEditor extends AbstractEditor {
61  
62      private static final Logger LOG = Logger.getLogger(WorkItemOlemlEditor.class);
63      HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
64      ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
65      ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
66      BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
67  
68      private static WorkItemOlemlEditor workItemOlemlEditor = null;
69      private InstanceEditorFormDataHandler instanceEditorFormDataHandler = null;
70  
71      DocstoreClient docstoreClient = getDocstoreLocalClient();
72  
73      private OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService;
74  
75      private OleDeliverRequestDocumentHelperServiceImpl getOleDeliverRequestDocumentHelperService() {
76          if (oleDeliverRequestDocumentHelperService == null) {
77              oleDeliverRequestDocumentHelperService = new OleDeliverRequestDocumentHelperServiceImpl();
78          }
79          return oleDeliverRequestDocumentHelperService;
80      }
81  
82      public static WorkItemOlemlEditor getInstance() {
83          if (workItemOlemlEditor == null) {
84              workItemOlemlEditor = new WorkItemOlemlEditor();
85          }
86          return workItemOlemlEditor;
87      }
88  
89      private WorkItemOlemlEditor() {
90  
91      }
92  
93      @Override
94      public EditorForm loadDocument(EditorForm editorForm) {
95          WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
96  //        editorForm.setHeaderText("Instance Editor (Item)- OLEML Format");
97          editorForm.setHeaderText("Item");
98          editorForm.setHasLink(true);
99          String bibId = editorForm.getBibId();
100         String holdingsId = editorForm.getInstanceId();
101         String docId = editorForm.getDocId();
102         OleHoldings oleHoldings = new OleHoldings();
103         String docStoreData = null;
104         List<BibTree> bibTreeList = new ArrayList<>();
105         Date date = new Date();
106         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
107         String dateStr = sdf.format(date);
108         BibTree bibTree = null;
109         try {
110             bibTree = docstoreClient.retrieveBibTree(bibId);
111             bibTreeList.add(bibTree);
112             workInstanceOlemlForm.setBibTreeList(bibTreeList);
113             if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bibTree.getBib().getFormat())) {
114                 editorForm.setTitle(bibTree.getBib().getTitle() + " / " + bibTree.getBib().getAuthor());
115             }
116             Holdings holdings = docstoreClient.retrieveHoldings(holdingsId);
117             oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
118             workInstanceOlemlForm.setSelectedHolding(oleHoldings);
119         } catch (DocstoreException e) {
120             LOG.error(e);
121             DocstoreException docstoreException = (DocstoreException) e;
122             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
123                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
124             } else {
125                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
126             }
127             return workInstanceOlemlForm;
128         } catch (Exception e) {
129             LOG.error("Exception ", e);
130             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
131         }
132 
133         try {
134             if (StringUtils.isNotEmpty(docId)) {
135                 editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(docId));
136                 org.kuali.ole.docstore.common.document.Item itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
137                 docStoreData = itemDocument.getContent();
138                 Item item = itemOlemlRecordProcessor.fromXML(docStoreData);
139                 ensureAccessInformation(item);
140                 //TODO : set additional attributes
141                 if (item != null && item.getItemStatusEffectiveDate() != null) {
142                     String[] itemStatusEffectiveDate = item.getItemStatusEffectiveDate().split(" ");
143                     item.setItemStatusEffectiveDate(itemStatusEffectiveDate[0]);
144                 }
145                 String itemStatus = null;
146                 if (item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null) {
147                     itemStatus = item.getItemStatus().getCodeValue();
148                     workInstanceOlemlForm.setOldItemStatus(itemStatus);
149                 }
150 
151                 if (item.getDueDateTime() != null && !item.getDueDateTime().equals("")) {
152                     String dueDate = item.getDueDateTime();
153                     if (dueDate.contains(" ")) {
154                         DateUtil dateUtil = new DateUtil();
155                         String dueTime = null;
156                         try {
157                             dueTime = dateUtil.convertTo12HoursFormat(dueDate.split(" ")[1]);
158                         } catch (ParseException e) {
159                             LOG.error("Exception :", e);
160                             e.printStackTrace();
161                         }
162                         item.setDueDateTime(dueDate.split(" ")[0] + " " + dueTime);
163                     }
164                 }
165                 String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "ITEM_STATUS_READONLY");
166                 String[] itemArray = itemProperty.split(",");
167                 for (String status : itemArray) {
168                     if (status.equalsIgnoreCase(itemStatus)) {
169                         workInstanceOlemlForm.setItemStatusNonEditable(true);
170                         break;
171                     }
172                     workInstanceOlemlForm.setItemStatusNonEditable(false);
173                 }
174                 itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
175                 boolean editable;
176                 if (itemProperty != null) {
177                     editable = Boolean.valueOf(itemProperty);
178                     workInstanceOlemlForm.setHoldingsDataInItemReadOnly(editable);
179                 }
180                 editorForm.setStaffOnlyFlagForItem(itemDocument.isStaffOnly());
181                 editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
182                 editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
183                 editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
184                 editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
185 
186                 List<Note> notes = ensureAtleastOneNote(item.getNote());
187                 item.setNote(notes);
188                 workInstanceOlemlForm.setSelectedItem(item);
189                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
190                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
191                 //workInstanceOlemlForm.setMessage("Item record loaded successfully.");
192                 if (editorForm.getEditable().equalsIgnoreCase("false")) {
193                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
194                 } else {
195                     boolean hasPermission = canEditItem(GlobalVariables.getUserSession().getPrincipalId());
196                     if (hasPermission) {
197                         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
198                     } else {
199                         editorForm.setHideFooter(false);
200                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_ITEM);
201                     }
202                 }
203             } else {
204 
205                 Item item = new Item();
206                 String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
207                 String[] itemArray = null;
208                 if (itemProperty != null) {
209                     itemArray = itemProperty.split(",");
210                 }
211                 if (itemArray != null) {
212                     for (String status : itemArray) {
213                         if (status.equalsIgnoreCase("TRUE")) {
214                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
215                         } else if (status.equalsIgnoreCase("FALSE")) {
216                             workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
217                         }
218                     }
219                 }
220                 List<Note> notes = ensureAtleastOneNote(item.getNote());
221                 item.setNote(notes);
222                 ensureAccessInformation(item);
223                 workInstanceOlemlForm.setSelectedItem(item);
224                 this.addItemInformation(editorForm);
225                 editorForm.setStaffOnlyFlagForItem(false);
226                 editorForm.setItemCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
227                 editorForm.setItemCreatedDate(dateStr);
228                 editorForm.setItemUpdatedBy(null);
229                 editorForm.setItemUpdatedDate(null);
230                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
231                 boolean hasPermission = canCreateItem(GlobalVariables.getUserSession().getPrincipalId());
232                 if (hasPermission) {
233                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
234                             "item.details.new.message");
235                 } else {
236                     editorForm.setHideFooter(false);
237                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_CREATE_ITEM);
238                 }
239                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
240             }
241         } catch (DocstoreException e) {
242             LOG.error(e);
243             DocstoreException docstoreException = (DocstoreException) e;
244             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
245                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
246             } else {
247                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
248             }
249             return workInstanceOlemlForm;
250         } catch (Exception e) {
251             LOG.error("Exception ", e);
252             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
253         }
254         return workInstanceOlemlForm;
255     }
256 
257     private void ensureAccessInformation(Item item) {
258         if(item.getAccessInformation() == null) {
259             AccessInformation accessInformation = new AccessInformation();
260             Uri uri = new Uri();
261             uri.setValue("");
262             uri.setResolvable("");
263             accessInformation.setUri(uri);
264             item.setAccessInformation(accessInformation);
265         }
266     }
267 
268     @Override
269     public EditorForm saveDocument(EditorForm editorForm) {
270         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
271         Date date = new Date();
272         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
273         String dateStr = sdf.format(date);
274         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
275         String docId = editorForm.getDocId();
276         String instanceId = editorForm.getInstanceId();
277         String editorMessage = "";
278         String callNumber;
279         String prefix;
280         Bib bib = null;
281 //        editorForm.setHeaderText("Instance Editor (Item)- OLEML Format");
282         editorForm.setHeaderText("Item");
283         try {
284             bib = docstoreClient.retrieveBib(editorForm.getBibId());
285             if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bib.getFormat())) {
286                 editorForm.setTitle(bib.getTitle() + " / " + bib.getAuthor());
287             }
288         } catch (DocstoreException e) {
289             LOG.error(e);
290             DocstoreException docstoreException = (DocstoreException) e;
291             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
292                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
293             } else {
294                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
295             }
296             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
297             return workInstanceOlemlForm;
298         } catch (Exception e) {
299             LOG.error("Exception ", e);
300             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
301         }
302 
303         try {
304             if (StringUtils.isNotEmpty(docId)) {
305                 Item itemData = workInstanceOlemlForm.getSelectedItem();
306                 if (editorForm.getItemStatusSelection().equals("true")) {
307                     Format formatter = new SimpleDateFormat("MM/dd/yyyy");
308                     itemData.setItemStatusEffectiveDate(formatter.format(new Date()));
309                 }
310                 if (!itemData.isClaimsReturnedFlag()) {
311                     itemData.setClaimsReturnedNote(null);
312                     itemData.setClaimsReturnedFlagCreateDate(null);
313                 } else {
314                     getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(itemData.getItemIdentifier());
315                 }
316                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
317                 if (!isValidItemData(workInstanceOlemlForm)) {
318 //                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
319                     return workInstanceOlemlForm;
320                 }
321 
322                 String itemId = editorForm.getDocId();
323                 itemData.setItemIdentifier(itemId);
324                 String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(itemData);
325 
326                 ItemOleml itemOleml = new ItemOleml();
327                 itemOleml.setContent(itemXmlContent);
328                 itemOleml.setId(itemId);
329                 itemOleml.setType(editorForm.getDocType());
330                 itemOleml.setFormat(editorForm.getDocFormat());
331                 itemOleml.setUpdatedBy(user);
332                 itemOleml.setUpdatedOn(dateStr);
333                 itemOleml.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
334                 itemOleml.setCategory(editorForm.getDocCategory());
335                 long startTime = System.currentTimeMillis();
336                 try {
337                     docstoreClient.updateItem(itemOleml);
338                 } catch (DocstoreException e) {
339                     LOG.error(e);
340                     DocstoreException docstoreException = (DocstoreException) e;
341                     if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
342                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
343                     } else {
344                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
345                     }
346 
347                     Holdings holdings = null;
348                     try {
349                         holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
350                     } catch (Exception e1) {
351                         LOG.error("Exception :", e1);
352                         docstoreException = (DocstoreException) e1;
353                         if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
354                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
355                         } else {
356                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
357                         }
358                     }
359                     String docStoreData = holdings.getContent();
360                     OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
361                     workInstanceOlemlForm.setSelectedHolding(oleHoldings);
362 
363                     getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
364                     return workInstanceOlemlForm;
365                 } catch (Exception e) {
366                     LOG.error("Exception ", e);
367                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
368                 }
369                 long endTime = System.currentTimeMillis();
370                 editorForm.setSolrTime(String.valueOf((endTime - startTime) / 1000));
371                 if(itemData.getLocation()!=null){
372                     String location = instanceEditorFormDataHandler.getLocationCode(itemData.getLocation().getLocationLevel());
373                     if(asrHelperService.isAnASRItem(location)){
374 
375                         Map<String,String> asrItemMap = new HashMap<String,String>();
376                         asrItemMap.put("itemBarcode",itemData.getAccessInformation().getBarcode());
377                         List<ASRItem> asrItems = (List<ASRItem>)businessObjectService.findMatching(ASRItem.class,asrItemMap);
378                         if(asrItems.size()==0){
379                             ASRItem asrItem = new ASRItem();
380                             if(itemData.getAccessInformation()!=null && itemData.getAccessInformation().getBarcode()!=null){
381                                 asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
382                             }
383                             if(bib.getTitle()!=null){
384                                 asrItem.setTitle((bib.getTitle().length()>37)?bib.getTitle().substring(0,36):bib.getTitle());
385                             }
386                             if(bib.getAuthor()!=null){
387                                 asrItem.setAuthor((bib.getAuthor().length()>37)?bib.getAuthor().substring(0,36):bib.getAuthor());
388                             }
389                             if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()){
390                                 callNumber=(itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
391                                 prefix=itemData.getCallNumber().getPrefix()!=null&&!itemData.getCallNumber().getPrefix().isEmpty()?itemData.getCallNumber().getPrefix():"";
392                                 asrItem.setCallNumber(prefix+" "+callNumber);
393                             }
394                             else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
395                                 callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
396                                 prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
397                                 asrItem.setCallNumber(prefix+" "+callNumber);
398                             }
399                             businessObjectService.save(asrItem);
400                         }
401                     }
402                 }else if(workInstanceOlemlForm.getSelectedHolding().getLocation()!=null){
403                     OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
404                     String location = oleHoldings.getLocation().getLocationLevel().getName();
405                     if(asrHelperService.isAnASRItem(location)){
406                         Map<String,String> asrItemMap = new HashMap<String,String>();
407                         asrItemMap.put("itemBarcode",itemData.getAccessInformation().getBarcode());
408                         List<ASRItem> asrItems = (List<ASRItem>)businessObjectService.findMatching(ASRItem.class,asrItemMap);
409                         if(asrItems.size()==0){
410                             ASRItem asrItem = new ASRItem();
411                             if(itemData.getAccessInformation()!=null && itemData.getAccessInformation().getBarcode()!=null){
412                                 asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
413                             }
414                             if(bib.getTitle()!=null){
415                                 asrItem.setTitle((bib.getTitle().length()>37)?bib.getTitle().substring(0,36):bib.getTitle());
416                             }
417                             if(bib.getAuthor()!=null){
418                                 asrItem.setAuthor((bib.getAuthor().length()>37)?bib.getAuthor().substring(0,36):bib.getAuthor());
419                             }
420                             if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()){
421                                 callNumber=(itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
422                                 prefix=itemData.getCallNumber().getPrefix()!=null&&!itemData.getCallNumber().getPrefix().isEmpty()?itemData.getCallNumber().getPrefix():"";
423                                 asrItem.setCallNumber(prefix+" "+callNumber);
424                             }
425                             else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
426                                 callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
427                                 prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
428                                 asrItem.setCallNumber(prefix+" "+callNumber);
429 
430                             }
431                             businessObjectService.save(asrItem);
432                         }
433                     }
434                 }
435                 String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
436                 String[] itemArray = null;
437                 if (itemProperty != null) {
438                     itemArray = itemProperty.split(",");
439                 }
440                 for (String status : itemArray) {
441                     if (status.equalsIgnoreCase("TRUE")) {
442                         workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
443                     } else if (status.equalsIgnoreCase("FALSE")) {
444                         workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
445                     }
446                 }
447                 String holdingId = workInstanceOlemlForm.getSelectedHolding().getHoldingsIdentifier();
448                 OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
449                 String holdingXmlContent = getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
450                 Holdings holdings = docstoreClient.retrieveHoldings(holdingId);
451                 holdings.setBib(bib);
452                 holdings.setContent(holdingXmlContent);
453                 holdings.setCategory(editorForm.getDocCategory());
454                 holdings.setType(DocType.HOLDINGS.getCode());
455                 holdings.setFormat(editorForm.getDocFormat());
456                 docstoreClient.updateHoldings(holdings);
457                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
458                 if (!isValidHoldingsData(workInstanceOlemlForm)) {
459                     getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
460                     return workInstanceOlemlForm;
461                 }
462                 editorMessage = "item.record.update.message";
463 
464             } else {
465 
466                 if (!isValidItemData(workInstanceOlemlForm)) {
467 //                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
468                     return workInstanceOlemlForm;
469                 }
470                 String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
471                 Item oleItem = workInstanceOlemlForm.getSelectedItem();
472                 String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
473                 ItemOleml itemDoc = new ItemOleml();
474                 itemDoc.setCategory(DocCategory.WORK.getCode());
475                 itemDoc.setType(DocType.ITEM.getCode());
476                 itemDoc.setFormat(DocFormat.OLEML.getCode());
477                 itemDoc.setCreatedOn(dateStr);
478                 itemDoc.setCreatedBy(user);
479                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
480                 itemDoc.setContent(itemXmlContent);
481                 Holdings holdings = new PHoldings();
482                 holdings.setId(editorForm.getInstanceId());
483                 itemDoc.setHolding(holdings);
484                 long startTime = System.currentTimeMillis();
485                 try {
486                     docstoreClient.createItem(itemDoc);
487                 } catch (Exception e) {
488                     LOG.error("Exception :", e);
489                     DocstoreException docstoreException = (DocstoreException) e;
490                     String errorCode = docstoreException.getErrorCode();
491                     if (StringUtils.isNotEmpty(errorCode)) {
492                         Map<String, String> paramsMap = docstoreException.getErrorParams();
493                         if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
494                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
495                         } else {
496                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
497                         }
498                     } else {
499                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
500                     }
501 
502                     try {
503                         holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
504                     } catch (Exception e1) {
505                         LOG.error("Exception :", e1);
506                         docstoreException = (DocstoreException) e1;
507                         if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
508                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
509                         } else {
510                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
511                         }
512                     }
513                     String docStoreData = holdings.getContent();
514                     OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
515                     workInstanceOlemlForm.setSelectedHolding(oleHoldings);
516 
517                     getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
518                     return workInstanceOlemlForm;
519                 }
520                 long endtime = System.currentTimeMillis();
521                 editorForm.setSolrTime(String.valueOf((endtime-startTime)/1000));
522                 if(oleItem.getLocation()!=null){
523                     String location =  oleItem.getLocation().getLocationLevel().getName();
524                     if (asrHelperService.isAnASRItem(location)) {
525                         Map<String, String> asrItemMap = new HashMap<String, String>();
526                         asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
527                         List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
528                         if (asrItems.size() == 0) {
529                             ASRItem asrItem = new ASRItem();
530                             if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
531                                 asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
532                             }
533                             if (bib.getTitle() != null) {
534                                 asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
535                             }
536                             if (bib.getAuthor() != null) {
537                                 asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
538                             }
539                             if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()){
540                                 callNumber=(oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
541                                 prefix=oleItem.getCallNumber().getPrefix()!=null&&!oleItem.getCallNumber().getPrefix().isEmpty()?oleItem.getCallNumber().getPrefix():"";
542                                 asrItem.setCallNumber(prefix+" "+callNumber);
543                             }
544                             else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
545                                 callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
546                                 prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
547                                 asrItem.setCallNumber(prefix+" "+callNumber);
548                             }
549                             businessObjectService.save(asrItem);
550                         }
551                     }
552                 }else if(workInstanceOlemlForm.getSelectedHolding().getLocation()!=null){
553                     OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
554                     String location = oleHoldings.getLocation().getLocationLevel().getName();
555                     if (asrHelperService.isAnASRItem(location)) {
556                         Map<String, String> asrItemMap = new HashMap<String, String>();
557                         asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
558                         List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
559                         if (asrItems.size() == 0) {
560                             ASRItem asrItem = new ASRItem();
561                             if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
562                                 asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
563                             }
564                             if (bib.getTitle() != null) {
565                                 asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
566                             }
567                             if (bib.getAuthor() != null) {
568                                 asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
569                             }
570                             if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()){
571                                 callNumber=(oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
572                                 prefix=oleItem.getCallNumber().getPrefix()!=null&&!oleItem.getCallNumber().getPrefix().isEmpty()?oleItem.getCallNumber().getPrefix():"";
573                                 asrItem.setCallNumber(prefix+" "+callNumber);
574                             }
575                             else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
576                                 callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
577                                 prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
578                                 asrItem.setCallNumber(prefix+" "+callNumber);
579 
580                             }
581                             businessObjectService.save(asrItem);
582                         }
583                     }
584                 }
585                 editorForm.setDocId(itemDoc.getId());
586                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
587                 editorMessage = "item.record.load.message";
588             }
589         } catch (Exception e) {
590             LOG.error("Exception :", e);
591             DocstoreException docstoreException = (DocstoreException) e;
592             if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
593                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
594             } else {
595                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
596             }
597             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
598             return workInstanceOlemlForm;
599         }
600         org.kuali.ole.docstore.common.document.Item itemDocument = null;
601         try {
602             Holdings holdings = null;
603             try {
604                 holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
605             } catch (Exception e) {
606                 LOG.error("Exception :", e);
607                 DocstoreException docstoreException = (DocstoreException) e;
608                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
609                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
610                 } else {
611                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
612                 }
613             }
614             String docStoreData = holdings.getContent();
615             OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
616             workInstanceOlemlForm.setSelectedHolding(oleHoldings);
617             try {
618                 itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
619             } catch (DocstoreException e) {
620                 LOG.error(e);
621                 DocstoreException docstoreException = (DocstoreException) e;
622                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
623                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
624                 } else {
625                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
626                 }
627                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
628                 return workInstanceOlemlForm;
629             } catch (Exception e) {
630                 LOG.error("Exception ", e);
631                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
632             }
633             Item item = itemOlemlRecordProcessor.fromXML(itemDocument.getContent());
634             editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(item.getItemIdentifier()));
635             editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
636             editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
637             editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
638             editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
639             workInstanceOlemlForm.setSelectedItem(item);
640             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
641             GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
642         } catch (Exception e) {
643             LOG.error("Exception :", e);
644             GlobalVariables.getMessageMap().clearErrorMessages();
645             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.submit.fail.message");
646         }
647         if(workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier()!=null){
648             String poId=workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier();
649             Map<String,String> map=new HashMap<>();
650             map.put("poItemId",poId);
651             List<OLELinkPurapDonor> oleLinkPurapDonor= (List<OLELinkPurapDonor>)KRADServiceLocator.getBusinessObjectService().findMatching(OLELinkPurapDonor.class,map);
652             if(workInstanceOlemlForm.getSelectedItem().getDonorInfo().size()>0){
653                 KRADServiceLocator.getBusinessObjectService().deleteMatching(OLELinkPurapDonor.class,map);
654                 for(DonorInfo donorInfo:workInstanceOlemlForm.getSelectedItem().getDonorInfo()){
655                     if(donorInfo.getDonorCode()!=null&&!donorInfo.getDonorCode().isEmpty()){
656                         map.clear();
657                         map.put("donorCode",donorInfo.getDonorCode());
658                         OLELinkPurapDonor newOleLinkPurapDonor=new OLELinkPurapDonor();
659                         List<OLEDonor> oleDonors= (List<OLEDonor>)KRADServiceLocator.getBusinessObjectService().findMatching(OLEDonor.class, map);
660                         map.clear();
661                         map.put("poItemId",poId);
662                         List<OleCopy> oleCopy= (List<OleCopy>)KRADServiceLocator.getBusinessObjectService().findMatching(OleCopy.class, map);
663                         if (oleCopy!=null && oleCopy.size()>0){
664                             newOleLinkPurapDonor.setCorrectionItemId(oleCopy.get(0).getCorrectionItemId());
665                             newOleLinkPurapDonor.setReqItemId(oleCopy.get(0).getReqItemId());
666                             newOleLinkPurapDonor.setPoDocNum(oleCopy.get(0).getPoDocNum());
667                             newOleLinkPurapDonor.setReceivingItemId(oleCopy.get(0).getReceivingItemId());
668                             newOleLinkPurapDonor.setDonorId(oleDonors.get(0).getDonorId());
669                             newOleLinkPurapDonor.setDonorCode(donorInfo.getDonorCode());
670                             newOleLinkPurapDonor.setPoItemId(Integer.parseInt(poId));
671                             KRADServiceLocator.getBusinessObjectService().save(newOleLinkPurapDonor);
672                         }
673                         map.clear();
674                     }
675                 }
676             }
677             else{
678                 KRADServiceLocator.getBusinessObjectService().deleteMatching(OLELinkPurapDonor.class,map);
679             }
680         }
681         // To remove existing item from bib tree
682         removeDocumentFromTree(editorForm);
683         // To add new item or updated item in bib tree
684         addItemToBibTree(workInstanceOlemlForm.getBibTreeList(), itemDocument);
685         return workInstanceOlemlForm;
686     }
687 
688     /**
689      * This methods adds the new item or updated item to the bib tree to build left pane tree.
690      * @param bibTreeList
691      * @param selectedItemDocument
692      */
693     private void addItemToBibTree(List<BibTree> bibTreeList, org.kuali.ole.docstore.common.document.Item selectedItemDocument) {
694         if (CollectionUtils.isNotEmpty(bibTreeList)) {
695             for (BibTree bibTree : bibTreeList) {
696                 if (CollectionUtils.isNotEmpty(bibTree.getHoldingsTrees())) {
697                     for (HoldingsTree holdingsTree : bibTree.getHoldingsTrees()) {
698                         if (null != holdingsTree.getHoldings() && null != selectedItemDocument.getHolding()) {
699                             String holdingsId = holdingsTree.getHoldings().getId();
700                             String selectedItemHoldingsId = selectedItemDocument.getHolding().getId();
701                             if (null != holdingsId && null != selectedItemHoldingsId) {
702                                 if (holdingsId.equals(selectedItemHoldingsId)) {
703                                     holdingsTree.setHoldings(selectedItemDocument.getHolding());
704                                     holdingsTree.getItems().add(selectedItemDocument);
705                                 }
706                             }
707                         }
708                     }
709                 }
710             }
711         }
712     }
713 
714     @Override
715     public EditorForm createNewRecord(EditorForm editorForm, BibTree bibTree) {
716 
717         if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
718             editorForm.setNeedToCreateInstance(true);
719         }
720         editNewRecord(editorForm, bibTree);
721         return editorForm.getDocumentForm();
722     }
723 
724     @Override
725     public EditorForm editNewRecord(EditorForm editorForm, BibTree bibTree) {
726         WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
727         if ((editorForm.getDocumentForm() instanceof WorkInstanceOlemlForm)) {
728             workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
729             workInstanceOlemlForm.setViewId(editorForm.getDocumentForm().getViewId());
730         }
731 
732         workInstanceOlemlForm.setDocCategory("work");
733         workInstanceOlemlForm.setDocType("item");
734         workInstanceOlemlForm.setDocFormat("oleml");
735 
736         if (bibTree != null && bibTree.getHoldingsTrees() != null) {
737             HoldingsTree holdingsTree = bibTree.getHoldingsTrees().get(0);
738             if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
739 //                editorForm.setHeaderText("Import Bib Step-4 Instance Editor (Item)- OLEML Format");
740                 editorForm.setHeaderText("Import Bib Step-4 Item");
741                 // validate user entered holding data before going to item tab
742                 if (!isValidHoldingsData(workInstanceOlemlForm)) {
743                     return workInstanceOlemlForm;
744                 }
745                 holdingsTree.getHoldings().setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
746                 holdingsTree.getHoldings().setCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
747                 Item item = itemOlemlRecordProcessor.fromXML(holdingsTree.getItems().get(0).getContent());
748                 List<Note> notes = ensureAtleastOneNote(item.getNote());
749                 item.setNote(notes);
750                 workInstanceOlemlForm.setSelectedItem(item);
751                 workInstanceOlemlForm.setViewId("WorkItemViewPage");
752                 //workInstanceOlemlForm.setMessage("Please enter details for new Item record.");
753                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
754                         "item.details.new.message");
755             } else if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkItemViewPage")) {
756                 if (!isValidItemData(workInstanceOlemlForm)) {
757                     return workInstanceOlemlForm;
758                 }
759                 Item item = workInstanceOlemlForm.getSelectedItem();
760                 Map<String, String> mapObject = new HashMap<String, String>();
761                 String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
762                 try {
763                     String holdingXmlContent = getInstanceEditorFormDataHandler()
764                             .buildHoldingContent(workInstanceOlemlForm.getSelectedHolding());
765                     holdingsTree.getHoldings().setContent(holdingXmlContent);
766 
767                     String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(item, staffOnlyFlagForItem);
768                     holdingsTree.getItems().get(0).setContent(itemXmlContent);
769 
770                 } catch (Exception e) {
771                     LOG.error("Exception :", e);
772                     StringBuffer instanceEditorErrorMessage = new StringBuffer(
773                             OLEConstants.INSTANCE_EDITOR_FAILURE).append(" :: \n" + e.getMessage());
774                     workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
775                     LOG.error(instanceEditorErrorMessage);
776                 }
777             }
778         }
779         editorForm.setDocumentForm(workInstanceOlemlForm);
780         return editorForm;
781     }
782 
783     @Override
784     public String saveDocument(BibTree bibTree, EditorForm editorForm) {
785         String responseFromDocstore = "success";
786         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
787         if (bibTree != null) {
788             try {
789                 docstoreClient.createBibTree(bibTree);
790             } catch (DocstoreException e) {
791                 LOG.error(e);
792                 DocstoreException docstoreException = (DocstoreException) e;
793                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
794                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
795                 } else {
796                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
797                 }
798             } catch (Exception e) {
799                 LOG.error("Exception ", e);
800                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
801             }
802         }
803         editorForm.setDocumentForm(workInstanceOlemlForm);
804         return responseFromDocstore;
805     }
806 
807 
808     /**
809      * Gets the InstanceEditorFormDataHandler attribute.
810      *
811      * @return Returns InstanceEditorFormDataHandler.
812      */
813     private InstanceEditorFormDataHandler getInstanceEditorFormDataHandler() {
814         if (null == instanceEditorFormDataHandler) {
815             instanceEditorFormDataHandler = new InstanceEditorFormDataHandler();
816         }
817         return instanceEditorFormDataHandler;
818     }
819 
820     private List<Note> ensureAtleastOneNote(List<Note> notes) {
821         if (notes == null) {
822             notes = new ArrayList<Note>();
823         }
824         if (notes.size() == 0) {
825             Note note = new Note();
826             notes.add(note);
827         }
828         return notes;
829     }
830 
831     private boolean canCreateItem(String principalId) {
832         PermissionService service = KimApiServiceLocator.getPermissionService();
833         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_ADD_ITEM);
834     }
835 
836     private boolean canEditItem(String principalId) {
837         PermissionService service = KimApiServiceLocator.getPermissionService();
838         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_EDIT_ITEM);
839     }
840 
841     private void addItemInformation(EditorForm editorForm) {
842         //TODO: do as per tree structure
843     }
844 
845     /**
846      * Validates the item data and returns true if it is valid
847      *
848      * @param workInstanceOlemlForm
849      * @return
850      */
851     private boolean isValidItemData(WorkInstanceOlemlForm workInstanceOlemlForm) {
852         Item item = workInstanceOlemlForm.getSelectedItem();
853         boolean isValidItem = true;
854 //        StringBuffer stringBuffer = new StringBuffer();
855         String oldItemStatus = workInstanceOlemlForm.getOldItemStatus();
856         String itemStatus = item.getItemStatus().getCodeValue();
857         String itemProperty = getInstanceEditorFormDataHandler()
858                 .getParameter(OLEConstants.DESC_NMSPC, OLEConstants.DESCRIBE_COMPONENT, OLEParameterConstants.ITEM_STATUS_READONLY);
859         String[] itemArray = itemProperty.split(",");
860         //If current item status is changed when compared with previous status
861         if ((org.apache.commons.lang.StringUtils.isNotEmpty(itemStatus)) && (!itemStatus.equals(oldItemStatus))) {
862             for (String status : itemArray) {
863                 if (status.equalsIgnoreCase(itemStatus)) {
864 //                    stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_INVALID + "</font>");
865                     //workInstanceOlemlForm.setMessage(stringBuffer.toString());
866                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "invalid.item.status");
867                     return false;
868                 }
869             }
870         }
871         String location = "";
872         String holdingsLocation = "";
873         if (item.getLocation() != null) {
874             location = item.getLocation().getLocationLevel().getName();
875         }
876         OleHoldings holdings = workInstanceOlemlForm.getSelectedHolding();
877         if (holdings.getLocation() != null) {
878             holdingsLocation = holdings.getLocation().getLocationLevel().getName();
879         }
880 
881 
882         //Display error message when item status is empty
883         if ( workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
884                 (item.getItemStatus() == null || item.getItemStatus().getCodeValue() == "" ||
885                         item.getItemStatus().getCodeValue().length() < 0)) {
886             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_ERRORMESSAGE + "</font>");
887             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus.codeValue", "error.item.status.required");
888             workInstanceOlemlForm.setValidInput(false);
889             isValidItem = false;
890         }
891 
892         //Display error message when item type is empty
893         if (workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
894                 (item.getItemType() == null || item.getItemType().getCodeValue() == null || item.getItemType().getCodeValue()=="" || item.getItemType().getCodeValue().length()==0 ||   item.getItemType().getCodeValue().length() < 0)) {
895 //            stringBuffer.append("<br>");
896             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERRORMESSAGE + "</font>");
897             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemType.codeValue", "error.item.type.required");
898             workInstanceOlemlForm.setValidInput(false);
899             isValidItem = false;
900         }
901 
902         if (holdingsLocation != null && holdingsLocation.length() != 0 && !isValidLocation(holdingsLocation)) {
903 //            stringBuffer.append("<br>");
904             GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
905             workInstanceOlemlForm.setValidInput(false);
906             isValidItem = false;
907         }
908         //Display error message when location is invalid
909         if (location != null && location.length() != 0 && !isValidLocation(location)) {
910 //            stringBuffer.append("<br>");
911             //stringBuffer.append("<font size='3' color='red'>Please enter the valid location.</font>");
912             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.location.locationLevel.name", "error.location");
913             workInstanceOlemlForm.setValidInput(false);
914             isValidItem = false;
915         }
916 
917         boolean hasPermission = canUpdateItemStatus(GlobalVariables.getUserSession().getPrincipalId());
918         if (hasPermission) {
919 //            if (org.apache.commons.lang.StringUtils.isEmpty(stringBuffer.toString())) {
920 //                isValidItem = true;
921 //            } else {
922 //                isValidItem = false;
923 //            }
924         } else {
925             //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERROR_MESSAGE + "</font>");
926             //workInstanceOlemlForm.setMessage(stringBuffer.toString());
927             GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.type.authorization");
928             return false;
929         }
930         return isValidItem;
931     }
932 
933     private boolean isValidLocation(String location) {
934 
935         List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
936         if (locationList != null && locationList.size() > 0) {
937             for (String locationValue : locationList) {
938                 if (locationValue.equalsIgnoreCase(location)) {
939                     return true;
940                 }
941             }
942         }
943         return false;
944     }
945 
946     private boolean canUpdateItemStatus(String principalId) {
947         LOG.debug("Inside the canUpdateItemStatus method");
948         PermissionService service = KimApiServiceLocator.getPermissionService();
949         return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_UPDATE_IEM_STATUS);
950     }
951 
952     /**
953      * Validates the Holdings data and returns true if it is valid
954      *
955      * @param workInstanceOlemlForm
956      * @return
957      */
958     private boolean isValidHoldingsData(WorkInstanceOlemlForm workInstanceOlemlForm) {
959         OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
960         String location = null;
961         if (oleHoldings != null && oleHoldings.getLocation() != null && oleHoldings.getLocation().getLocationLevel() != null) {
962             location = oleHoldings.getLocation().getLocationLevel().getName();
963         }
964         if (location != null && location.length() != 0 && !isValidLocation(location)) {
965             //workInstanceOlemlForm.setMessage("<font size='3' color='red'>Please enter valid location.</font>");
966             GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
967             workInstanceOlemlForm.setValidInput(false);
968             return false;
969         }
970         return true;
971     }
972 
973 
974     public EditorForm deleteVerify(EditorForm editorForm) {
975         //LOG.info("in instance editor class");
976         String docId = editorForm.getDocId();
977         String operation = "deleteVerify";
978         //        String responseXml = getResponseFromDocStore(editorForm, docId, operation);
979         //        LOG.info("deleteVerify responseXml-->" + responseXml);
980         //        editorForm.setDeleteVerifyResponse(responseXml);
981         editorForm.setShowDeleteTree(true);
982         editorForm.setHasLink(true);
983         //        Node<DocumentTreeNode, String> docTree = buildDocSelectionTree(responseXml);
984         List<String> uuidList = new ArrayList<>(0);
985         uuidList.add(editorForm.getDocId());
986         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
987         Node<DocumentTreeNode, String> docTree = null;
988         try {
989             docTree = documentSelectionTree.add(uuidList, editorForm.getDocType());
990         } catch (SolrServerException e) {
991             LOG.error("Exception :", e);
992             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
993         }
994         editorForm.getDocTree().setRootElement(docTree);
995         editorForm.setViewId("DeleteViewPage");
996         return editorForm;
997 
998     }
999 
1000     /**
1001      * This method deletes the item record from docstore by the doc id.
1002      * @param editorForm
1003      * @return
1004      * @throws Exception
1005      */
1006     public EditorForm delete(EditorForm editorForm) throws Exception {
1007         return deleteFromDocStore(editorForm);
1008     }
1009 
1010     @Override
1011     public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1012         String methodName = request.getParameter("methodToCall");
1013         if (methodName.equalsIgnoreCase("addItemNote")) {
1014             WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1015             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1016             index++;
1017             List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1018             itemNote.add(index, new Note());
1019             editorForm.setDocumentForm(workInstanceOlemlForm);
1020         } else if (methodName.equalsIgnoreCase("removeItemNote")) {
1021             WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1022             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1023             List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1024             if (itemNote.size() > 1) {
1025                 itemNote.remove(index);
1026             } else {
1027                 if (itemNote.size() == 1) {
1028                     itemNote.remove(index);
1029                     Note note = new Note();
1030                     itemNote.add(note);
1031                 }
1032             }
1033             editorForm.setDocumentForm(workInstanceOlemlForm);
1034         }
1035         return editorForm;
1036     }
1037 
1038     @Override
1039     public EditorForm bulkUpdate(EditorForm editorForm, List<String> ids) {
1040         WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1041         Date date = new Date();
1042         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
1043         String dateStr = sdf.format(date);
1044         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
1045         String docId = editorForm.getDocId();
1046         String instanceId = editorForm.getInstanceId();
1047         String editorMessage = "";
1048         Bib bib = null;
1049         editorForm.setHeaderText("Global Edit - Item");
1050 
1051         try {
1052 
1053             workInstanceOlemlForm.setGlobalEditFlag("true");
1054             if (!isValidItemData(workInstanceOlemlForm)) {
1055                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1056                 return workInstanceOlemlForm;
1057             }
1058             String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
1059             Item oleItem = workInstanceOlemlForm.getSelectedItem();
1060             String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
1061             ItemOleml itemDoc = new ItemOleml();
1062             itemDoc.setCategory(DocCategory.WORK.getCode());
1063             itemDoc.setType(DocType.ITEM.getCode());
1064             itemDoc.setFormat(DocFormat.OLEML.getCode());
1065             itemDoc.setCreatedOn(dateStr);
1066             itemDoc.setCreatedBy(user);
1067             String canUpdateStaffOnlyFlag = "false";
1068             if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("Y")) {
1069                 canUpdateStaffOnlyFlag = "true";
1070                 editorForm.setStaffOnlyFlagForItem(true);
1071                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1072             }
1073             else if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("N")) {
1074                 canUpdateStaffOnlyFlag = "true";
1075                 editorForm.setStaffOnlyFlagForItem(false);
1076                 itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1077             }
1078             itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
1079             itemDoc.setContent(itemXmlContent);
1080             /*Holdings holdings = new PHoldings();
1081             holdings.setId(editorForm.getInstanceId());
1082             itemDoc.setHolding(holdings);*/
1083             try {
1084                 getDocstoreClientLocator().getDocstoreClient().bulkUpdateItem(itemDoc,ids,canUpdateStaffOnlyFlag);
1085             } catch (Exception e) {
1086                 LOG.error("Exception :", e);
1087                 DocstoreException docstoreException = (DocstoreException) e;
1088                 String errorCode = docstoreException.getErrorCode();
1089                 if (StringUtils.isNotEmpty(errorCode)) {
1090                     Map<String, String> paramsMap = docstoreException.getErrorParams();
1091                     if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
1092                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
1093                     } else {
1094                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
1095                     }
1096                 } else {
1097                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1098                 }
1099                 getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1100                 return workInstanceOlemlForm;
1101             }
1102             editorForm.setDocId(itemDoc.getId());
1103             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1104             editorMessage = "item.record.load.message";
1105 
1106         } catch (Exception e) {
1107             LOG.error("Exception :", e);
1108             DocstoreException docstoreException = (DocstoreException) e;
1109             if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1110                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1111             } else {
1112                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1113             }
1114             getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1115             return workInstanceOlemlForm;
1116         }
1117         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
1118         return workInstanceOlemlForm;
1119     }
1120 }