View Javadoc
1   package org.kuali.ole.describe.controller;
2   
3   import org.apache.commons.collections.CollectionUtils;
4   import org.apache.commons.lang.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.ole.OLEConstants;
9   import org.kuali.ole.OleEditorResponseHandler;
10  import org.kuali.ole.deliver.bo.SystemGeneratedBill;
11  import org.kuali.ole.describe.bo.DocumentSelectionTree;
12  import org.kuali.ole.describe.bo.DocumentTreeNode;
13  import org.kuali.ole.describe.bo.MarcEditorControlField;
14  import org.kuali.ole.describe.bo.MarcEditorDataField;
15  import org.kuali.ole.describe.bo.MarcEditorFormDataHandler;
16  import org.kuali.ole.describe.bo.OleBibliographicRecordStatus;
17  import org.kuali.ole.describe.bo.marc.structuralfields.ControlFields;
18  import org.kuali.ole.describe.bo.marc.structuralfields.controlfield006.ControlField006Text;
19  import org.kuali.ole.describe.bo.marc.structuralfields.controlfield007.ControlField007Text;
20  import org.kuali.ole.describe.bo.marc.structuralfields.controlfield008.ControlField008;
21  import org.kuali.ole.describe.form.EditorForm;
22  import org.kuali.ole.describe.form.WorkBibMarcForm;
23  import org.kuali.ole.describe.form.WorkEInstanceOlemlForm;
24  import org.kuali.ole.describe.service.DiscoveryHelperService;
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.Item;
28  import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecord;
29  import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecords;
30  import org.kuali.ole.docstore.common.document.content.bib.marc.xstream.BibMarcRecordProcessor;
31  import org.kuali.ole.docstore.common.document.content.enums.DocCategory;
32  import org.kuali.ole.docstore.common.document.content.enums.DocFormat;
33  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
34  import org.kuali.ole.docstore.common.exception.DocstoreException;
35  import org.kuali.ole.docstore.engine.client.DocstoreLocalClient;
36  import org.kuali.ole.docstore.model.bo.WorkBibDocument;
37  import org.kuali.ole.docstore.model.bo.WorkHoldingsDocument;
38  import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
39  import org.kuali.ole.docstore.model.bo.WorkItemDocument;
40  import org.kuali.ole.docstore.model.enums.DocType;
41  import org.kuali.ole.docstore.model.xmlpojo.ingest.Response;
42  import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument;
43  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.ControlField;
44  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.DataField;
45  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.SubField;
46  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.WorkBibMarcRecord;
47  import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
48  import org.kuali.ole.docstore.validation.DocStoreValidationError;
49  import org.kuali.ole.docstore.validation.WorkBibMarcRecordValidator;
50  import org.kuali.ole.pojo.OleBibRecord;
51  import org.kuali.ole.pojo.OleEditorResponse;
52  import org.kuali.ole.select.bo.OLEEditorResponse;
53  import org.kuali.ole.select.businessobject.OleDocstoreResponse;
54  import org.kuali.ole.select.document.OLEEResourceInstance;
55  import org.kuali.ole.select.document.OLEEResourceRecordDocument;
56  import org.kuali.ole.select.service.impl.OleExposedWebServiceImpl;
57  import org.kuali.ole.service.OLEEResourceSearchService;
58  import org.kuali.ole.sys.context.SpringContext;
59  import org.kuali.rice.core.api.config.property.ConfigContext;
60  import org.kuali.rice.core.api.config.property.ConfigurationService;
61  import org.kuali.rice.core.api.exception.RiceRuntimeException;
62  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
63  import org.kuali.rice.core.api.util.tree.Node;
64  import org.kuali.rice.kim.api.identity.Person;
65  import org.kuali.rice.kim.api.identity.PersonService;
66  import org.kuali.rice.kim.api.permission.PermissionService;
67  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
68  import org.kuali.rice.krad.service.*;
69  import org.kuali.rice.krad.uif.UifParameters;
70  import org.kuali.rice.krad.util.GlobalVariables;
71  import org.kuali.rice.krad.util.KRADConstants;
72  
73  import javax.servlet.http.HttpServletRequest;
74  import java.text.SimpleDateFormat;
75  import java.util.*;
76  
77  /**
78   * Class for handling all editor operations for WorkBibMarc documents.
79   */
80  public class WorkBibMarcEditor extends AbstractEditor implements
81          DocumentEditor {
82  
83      private static final Logger LOG = Logger.getLogger(WorkBibMarcEditor.class);
84  
85      private MarcEditorFormDataHandler marcEditorFormDataHandler;
86      private BibMarcRecordProcessor bibMarcRecordProcessor = new BibMarcRecordProcessor();
87      private OLEEResourceSearchService oleEResourceSearchService;
88      private DocumentService documentService;
89      private String tokenId;
90      private static WorkBibMarcEditor workBibMarcEditor = new WorkBibMarcEditor();
91      private DocstoreClient docstoreClient = getDocstoreLocalClient();
92      private BusinessObjectService businessObjectService;
93  
94      public BusinessObjectService getBusinessObjectService() {
95          if (businessObjectService == null) {
96              businessObjectService = KRADServiceLocator.getBusinessObjectService();
97          }
98          return businessObjectService;
99      }
100 
101 
102     public static WorkBibMarcEditor getInstance() {
103         return workBibMarcEditor;
104     }
105 
106     private WorkBibMarcEditor() {
107     }
108 
109     public OLEEResourceSearchService getOleEResourceSearchService() {
110         if (oleEResourceSearchService == null) {
111             oleEResourceSearchService = GlobalResourceLoader.getService(OLEConstants.OLEEResourceRecord.ERESOURSE_SEARCH_SERVICE);
112         }
113         return oleEResourceSearchService;
114     }
115 
116     public DocumentService getDocumentService() {
117         if (this.documentService == null) {
118             this.documentService = KRADServiceLocatorWeb.getDocumentService();
119         }
120         return this.documentService;
121     }
122 
123     private boolean canEditBib(String principalId) {
124         PermissionService service = KimApiServiceLocator.getPermissionService();
125         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.MARC_EDITOR_EDIT_BIB);
126     }
127 
128     private boolean canAddBib(String principalId) {
129         PermissionService service = KimApiServiceLocator.getPermissionService();
130         return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.MARC_EDITOR_ADD_BIB);
131     }
132 
133     @Override
134     public EditorForm loadDocument(EditorForm editorForm) {
135         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
136         String docId = editorForm.getDocId();
137         //Modified title display for left pane
138         editorForm.setHasLink(true);
139         editorForm.setBibliographic(true);
140         workBibMarcForm.setHideFooter(true);
141         String parameter = getParameter(OLEConstants.APPL_ID_OLE, OLEConstants.DESC_NMSPC, OLEConstants
142                 .DESCRIBE_COMPONENT, OLEConstants.BIB_RENDER_PRINT);
143         editorForm.setShowPrint(Boolean.valueOf(parameter));
144         // When copied and cancelled
145         if (editorForm.isCopyFlag() && StringUtils.isBlank(docId)) {
146             if (CollectionUtils.isNotEmpty(editorForm.getBibTreeList())) {
147                 Bib bib = editorForm.getBibTreeList().get(0).getBib();
148                 if (null != bib) {
149                     docId = bib.getId();
150                     editorForm.setDocId(docId);
151                     editorForm.setNewDocument(false);
152                 }
153             }
154         }
155 
156         List<BibTree> bibTreeList = new ArrayList<>();
157         BibTree bibTree = null;
158         String directory = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(org.kuali.ole.sys.OLEConstants.EXTERNALIZABLE_HELP_URL_KEY);
159         editorForm.setExternalHelpUrl(directory+"/reference/webhelp/OLE/content/ch04s01.html#_Editors");
160         editorForm.setHeaderText("Bib");
161         if (null != docId && StringUtils.isNotEmpty(docId)) {
162             try {
163                 editorForm.setBibLocalIdentifier(docId);
164                 bibTree = docstoreClient.retrieveBibTree(docId);
165                 bibTreeList.add(bibTree);
166                 workBibMarcForm.setBibTreeList(bibTreeList);
167                 Bib bib = bibTree.getBib();
168                 BibMarcRecords bibMarcRecords = new BibMarcRecordProcessor().fromXML(bib.getContent());
169 
170 
171                 editorForm.setCreatedBy(bib.getCreatedBy());
172                 editorForm.setCreatedDate(bib.getCreatedOn());
173                 editorForm.setUpdatedBy(bib.getUpdatedBy());
174                 editorForm.setUpdatedDate(bib.getUpdatedOn());
175                 editorForm.setStatusUpdatedBy(bib.getStatusUpdatedBy());
176                 editorForm.setStatusUpdatedOn(bib.getStatusUpdatedOn());
177                 editorForm.setStaffOnlyFlagForBib(bib.isStaffOnly());
178 
179                 List<BibMarcRecord> bibMarcRecordList = bibMarcRecords.getRecords();
180                 BibMarcRecord bibMarcRecord = bibMarcRecordList.get(0);
181                 Collections.sort(bibMarcRecord.getDataFields());
182                 //editorForm.setTitle(getMarcFormDataHandler().buildMarcEditorTitleField(bibMarcRecord.getDataFields())+" / "+ DocumentUniqueIDPrefix.getDocumentId(bib.getId()));
183                 editorForm.setTitle(bib.getTitle() + " / " + bib.getAuthor() + " / " + DocumentUniqueIDPrefix.getDocumentId(bib.getId()));
184                 workBibMarcForm.setLeader(bibMarcRecord.getLeader());
185                 workBibMarcForm.setControlFields(getMarcFormDataHandler().buildMarcEditorControlFields(workBibMarcForm, bibMarcRecord.getControlFields()));
186                 List<MarcEditorDataField> marcEditorDataFields = new ArrayList<MarcEditorDataField>();
187                 marcEditorDataFields = getMarcFormDataHandler().buildMarcEditorDataFields(bibMarcRecord.getDataFields());
188                 if (!editorForm.getEditable().equalsIgnoreCase("true")) {
189                     for (MarcEditorDataField marcEditorDataField : marcEditorDataFields) {
190                         String tempValue = null;
191                         if (marcEditorDataField.getValue() != null) {
192                             tempValue = marcEditorDataField.getValue().replace("&quot;", "\"");
193                             tempValue = tempValue.replaceAll("&nbsp;", " ");
194                             marcEditorDataField.setValue(tempValue);
195                         }
196                     }
197                 }
198                 if (CollectionUtils.isEmpty(marcEditorDataFields)) {
199                     marcEditorDataFields.add(new MarcEditorDataField());
200                 }
201                 workBibMarcForm.setDataFields(marcEditorDataFields);
202                 BusinessObjectService boService = getBusinessObjectService();
203                 Map parentCriteria = new HashMap();
204                 String bibStatusName = bib.getStatus();
205                 parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
206                 OleBibliographicRecordStatus bibliographicRecordStatus = boService.findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
207                 editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
208                 //workBibMarcForm.setMessage("Please edit details for the Bib record.");
209                 if (editorForm.getEditable().equalsIgnoreCase("true")) {
210                     boolean hasEditPermission = canEditBib(GlobalVariables.getUserSession().getPrincipalId());
211                     if (!hasEditPermission) {
212                         editorForm.setHideFooter(false);
213                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_BIB_EDIT_AUTHORIZATION);
214                     } else {
215                         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.record");
216                     }
217                 } else {
218                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.record");
219                 }
220             } catch (DocstoreException e) {
221                 LOG.error(e);
222                 DocstoreException docstoreException = (DocstoreException) e;
223                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
224                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
225                 } else {
226                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
227                 }
228                 return workBibMarcForm;
229             } catch (Exception e) {
230                 LOG.error("Exception ", e);
231                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
232             }
233         } else {
234             //workBibMarcForm.setMessage("Please enter details for new Bib record.");
235             boolean hasAddPermission = canAddBib(GlobalVariables.getUserSession().getPrincipalId());
236             if (!hasAddPermission) {
237                 workBibMarcForm.setEditable("false");
238                 editorForm.setHideFooter(false);
239                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_BIB_CREATE_AUTHORIZATION);
240             } else {
241                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.new.record");
242                 if (editorForm.getViewId().equalsIgnoreCase(OLEConstants.EDITOR_WORKFORM_VIEW)) {
243                     workBibMarcForm.getDataFields().clear();
244                     addDefaultDataFields(workBibMarcForm);
245                 }
246             }
247 
248         }
249         // Add a node for this document to the left pane tree.
250         addDocumentToTree(editorForm);
251         setControlFields(workBibMarcForm);
252         if (StringUtils.isNotBlank(editorForm.getViewId())) {
253             if (editorForm.getViewId().equalsIgnoreCase(OLEConstants.EDITOR_VIEW)) {
254                 workBibMarcForm.setViewId(OLEConstants.WORK_BIB_EDITOR_VIEW_PAGE);
255             } else if (editorForm.getViewId().equalsIgnoreCase(OLEConstants.EDITOR_WORKFORM_VIEW)) {
256                 workBibMarcForm.setViewId(OLEConstants.EDITOR_WORKFORM_VIEW_PAGE);
257                 editorForm.setWorkFormViewFlag(true);
258             }
259         }
260         return workBibMarcForm;
261     }
262 
263     /**
264      * This method adds the default data fields for Editor Workform.
265      * @param workBibMarcForm
266      */
267     private void addDefaultDataFields(WorkBibMarcForm workBibMarcForm) {
268         List<MarcEditorDataField> dataFields = new ArrayList<>();
269         String[] subFields = new String[]{OLEConstants.A};
270         dataFields.add(getDataField(OLEConstants.DATAFIELD_020, OLEConstants.DELIMITER_HASH, OLEConstants.DELIMITER_HASH, subFields));
271         dataFields.add(getDataField(OLEConstants.DATAFIELD_022, OLEConstants.DELIMITER_HASH, OLEConstants.DELIMITER_HASH, subFields));
272         dataFields.add(getDataField(OLEConstants.DATAFIELD_100, OLEConstants.INDICATOR_1, OLEConstants.DELIMITER_HASH, subFields));
273         dataFields.add(getDataField(OLEConstants.DATAFIELD_245, OLEConstants.INDICATOR_1, OLEConstants.INDICATOR_0, subFields));
274         dataFields.add(getDataField(OLEConstants.DATAFIELD_250, OLEConstants.DELIMITER_HASH, OLEConstants.DELIMITER_HASH, subFields));
275         dataFields.add(getDataField(OLEConstants.DATAFIELD_260, OLEConstants.DELIMITER_HASH, OLEConstants.DELIMITER_HASH, new String[]{OLEConstants.A, OLEConstants.B, OLEConstants.C}));
276         dataFields.add(getDataField(OLEConstants.DATAFIELD_300, OLEConstants.DELIMITER_HASH, OLEConstants.DELIMITER_HASH, subFields));
277         dataFields.add(getDataField(OLEConstants.DATAFIELD_490, OLEConstants.INDICATOR_0, OLEConstants.DELIMITER_HASH, subFields));
278         workBibMarcForm.setDataFields(dataFields);
279 
280     }
281 
282     /**
283      * This method is used to get the marc editor data field object.
284      * @param tag
285      * @param ind1
286      * @param ind2
287      * @param subFields
288      * @return
289      */
290     private MarcEditorDataField getDataField(String tag, String ind1, String ind2, String[] subFields) {
291         MarcEditorDataField dataField = new MarcEditorDataField();
292         dataField.setTag(tag);
293         dataField.setInd1(ind1);
294         dataField.setInd2(ind2);
295         StringBuilder valueBuilder = new StringBuilder();
296         for (String subField : subFields) {
297             if (tag.equalsIgnoreCase(OLEConstants.DATAFIELD_260)) {
298                 if (subField.equalsIgnoreCase(OLEConstants.A)) {
299                     dataField.setValue260a(OLEConstants.PIPE + subField + " ");
300                 } else if (subField.equalsIgnoreCase(OLEConstants.B)) {
301                     dataField.setValue260b(OLEConstants.PIPE + subField + " ");
302                 } else if (subField.equalsIgnoreCase(OLEConstants.C)) {
303                     dataField.setValue260c(OLEConstants.PIPE + subField + " ");
304                 }
305             } else {
306                 valueBuilder.append(OLEConstants.PIPE + subField + " ");
307             }
308         }
309         if (!tag.equalsIgnoreCase(OLEConstants.DATAFIELD_260)) {
310             dataField.setValue(valueBuilder.toString());
311         }
312         return dataField;
313     }
314     @Override
315     public EditorForm saveDocument(EditorForm editorForm) {
316 
317         Bib bib = null;
318         String editorStatusMessage = "";
319         editorForm.setHasLink(true);
320         editorForm.setBibliographic(true);
321         WorkBibMarcForm workBibMarcForm = (WorkBibMarcForm) editorForm.getDocumentForm();
322         List<MarcEditorDataField> emptyDataFieldList = new ArrayList<>();
323 
324         if (editorForm.isWorkFormViewFlag()) {
325             editorForm.setOleBibliographicRecordStatus(new OleBibliographicRecordStatus());
326             workBibMarcForm.setLeader(OLEConstants.LEADER_DEFAULT);
327             if (null != workBibMarcForm.getMarcControlFields()) {
328                 ControlFields controlFields = workBibMarcForm.getMarcControlFields();
329                 if (null == controlFields.getControlField008()) {
330                     ControlField008 controlField008 = new ControlField008();
331                     controlField008.setRawText(OLEConstants.DEFAULT_008);
332                     controlFields.setControlField008(controlField008);
333                 } else {
334                     controlFields.getControlField008().setRawText(OLEConstants.DEFAULT_008);
335                 }
336             }
337             append260Values(workBibMarcForm);
338             emptyDataFieldList = removeEmptyDataFields(workBibMarcForm);
339             workBibMarcForm.getDataFields().removeAll(emptyDataFieldList);
340         }
341         String bibliographicRecordStatusCode = editorForm.getOleBibliographicRecordStatus()
342                 .getBibliographicRecordStatusCode();
343         boolean staffOnlyFlag = editorForm.isStaffOnlyFlagForBib();
344         tokenId = editorForm.getTokenId();
345         String eResourceID = editorForm.geteResourceId();
346         String holdingsId = "";
347         HoldingsTree holdingsTree = null;
348         buildControlFieldList(workBibMarcForm);
349         if (!editorForm.isWorkFormViewFlag()) {
350             buildDataFieldList(workBibMarcForm);
351         }
352         boolean valid = validateMarcEditorData(workBibMarcForm);
353         if (valid) {
354             buildLeader(workBibMarcForm);
355         } else {
356             workBibMarcForm.getDataFields().addAll(emptyDataFieldList);
357             Collections.sort(workBibMarcForm.getDataFields());
358         }
359         Date date = new Date();
360         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
361         String dateStr = sdf.format(date);
362         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
363         BusinessObjectService boService = getBusinessObjectService();
364         OleBibliographicRecordStatus bibliographicRecordStatus = null;
365         if (bibliographicRecordStatusCode != null) {
366             Map parentCriteria = new HashMap();
367             parentCriteria.put("bibliographicRecordStatusCode", bibliographicRecordStatusCode);
368             bibliographicRecordStatus = boService.findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
369         }
370         if (valid) {
371             MarcEditorFormDataHandler marcEditorFormDataHandler = getMarcFormDataHandler();
372             String content = marcEditorFormDataHandler.buildBibRecordForDocStore(workBibMarcForm);
373             String uuid = editorForm.getDocId();
374 
375 
376             try {
377                 if (null != uuid && !uuid.trim().equals("")) {
378                     editorForm.setBibLocalIdentifier(uuid);
379                     if (boService != null) {
380                         try {
381                             bib = docstoreClient.retrieveBib(uuid);
382                         }
383                         catch (Exception e) {
384                             LOG.error("Exception :", e);
385                             DocstoreException docstoreException = (DocstoreException) e;
386                             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
387                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
388                             } else {
389                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
390                             }
391                             return workBibMarcForm;
392                         }
393                         if (bibliographicRecordStatus != null) {
394                             bib.setStatus(bibliographicRecordStatus.getBibliographicRecordStatusName());
395 
396                         } else {
397                             bib.setStatus("");
398                         }
399                     }
400                     bib.setStaffOnly(staffOnlyFlag);
401                     bib.setContent(content);
402                     bib.setUpdatedBy(GlobalVariables.getUserSession().getPrincipalName());
403                     bib.setUpdatedOn(dateStr);
404                     bib.deserializeContent(bib);
405                     long startTime = System.currentTimeMillis();
406                     try {
407                         bib = docstoreClient.updateBib(bib);
408                     }
409                     catch (Exception e) {
410                         DocstoreException docstoreException = (DocstoreException) e;
411                         if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
412                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode(), bib.getId());
413                         } else {
414                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
415                         }
416                         return workBibMarcForm;
417                     }
418                     long endTime = System.currentTimeMillis();
419                     editorForm.setSolrTime(String.valueOf((endTime-startTime)/1000));
420                     editorStatusMessage = OLEConstants.BIB_EDITOR_UPDATE_SUCCESS;
421                     String bibStatusName = bib.getStatus();
422                     editorForm.setCreatedBy(bib.getCreatedBy());
423                     editorForm.setCreatedDate(bib.getCreatedOn());
424                     editorForm.setUpdatedBy(bib.getUpdatedBy());
425                     editorForm.setUpdatedDate(bib.getUpdatedOn());
426                     editorForm.setStatusUpdatedOn(bib.getStatusUpdatedOn());
427                     editorForm.setStatusUpdatedBy(bib.getStatusUpdatedBy());
428                     Map parentCriteria = new HashMap();
429                     parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
430                     bibliographicRecordStatus = boService
431                             .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
432                     if (bibliographicRecordStatus != null) {
433                         editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
434                     }
435                     //TODO:Edit the processResponse methods
436                     //processResponse(responseFromDocstore, workBibMarcForm, uuid);
437 
438                 } else {
439                     BibTree bibTree = new BibTree();
440                     bib = new BibMarc();
441                     bib.setCategory(DocCategory.WORK.getCode());
442                     bib.setType(DocType.BIB.getCode());
443                     bib.setFormat(DocFormat.MARC.getCode());
444                     bib.setCreatedBy(user);
445                     bib.setCreatedOn(dateStr);
446                     bib.setStaffOnly(staffOnlyFlag);
447                     bib.setContent(content);
448                     if (bibliographicRecordStatus != null) {
449                         bib.setStatus(bibliographicRecordStatus.getBibliographicRecordStatusName());
450                     } else {
451                         bib.setStatus("");
452                     }
453                     bibTree.setBib(bib);
454                     holdingsTree = getHoldingsTree(eResourceID);
455                     if (holdingsTree != null && holdingsTree.getHoldings() != null) {
456                         holdingsTree.getHoldings().setCreatedBy(user);
457                         holdingsTree.getHoldings().setCreatedOn(dateStr);
458                     /*if (!(StringUtils.isNotEmpty(eResourceID) || (StringUtils.isNotBlank(editorForm.getLinkToOrderOption()) && editorForm.getLinkToOrderOption().equals(OLEConstants.NB_ELECTRONIC)))) {
459                         holdingsTree.getItems().get(0).setCreatedBy(user);
460                     }*/
461                         bibTree.getHoldingsTrees().add(holdingsTree);
462                     }
463                     try {
464                         try {
465                             docstoreClient.createBib(bib);
466                         } catch (DocstoreException e) {
467                             LOG.error("Exception :", e);
468                             DocstoreException docstoreException = (DocstoreException) e;
469                             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
470                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
471                             } else {
472                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
473                             }
474                             return workBibMarcForm;
475                         } catch (Exception e) {
476                             LOG.error("Exception ", e);
477                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
478                         }
479                         if (holdingsTree != null && holdingsTree.getHoldings() != null) {
480                             holdingsTree.getHoldings().setBib(bib);
481                             try {
482                                 docstoreClient.createHoldingsTree(holdingsTree);
483                             } catch (DocstoreException e) {
484                                 LOG.error("Exception :", e);
485                                 DocstoreException docstoreException = (DocstoreException) e;
486                                 if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
487                                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
488                                 } else {
489                                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
490                                 }
491                                 return workBibMarcForm;
492                             } catch (Exception e) {
493                                 LOG.error("Exception ", e);
494                                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response", e.getMessage());
495                             }
496                         }
497                         editorForm.setDocId(bib.getId());
498                         editorForm.setBibId(bib.getId());
499                         editorForm.setCreatedBy(bib.getCreatedBy());
500                         editorForm.setCreatedDate(bib.getCreatedOn());
501                         editorForm.setUpdatedBy(bib.getUpdatedBy());
502                         editorForm.setUpdatedDate(bib.getUpdatedOn());
503                         editorForm.setStatusUpdatedOn(bib.getStatusUpdatedOn());
504                         editorForm.setStatusUpdatedBy(bib.getStatusUpdatedBy());
505                         List<BibTree> bibTreeList = new ArrayList<>();
506                         bibTreeList.add(bibTree);
507                         editorForm.setBibTreeList(bibTreeList);
508                         editorStatusMessage = OLEConstants.BIB_EDITOR_CREATE_SUCCESS;
509                         //TODO:Edit the processResponse methods
510                         //processResponse(responseFromDocstore, workBibMarcForm, uuid);
511                         processResponse(bib,editorForm.getLinkToOrderOption());
512                         workBibMarcForm.setLeader("");
513                         workBibMarcForm.setControlFields(Arrays.asList(new MarcEditorControlField()));
514                         workBibMarcForm.setDataFields(Arrays.asList(new MarcEditorDataField()));
515                         workBibMarcForm.setUuid("");
516                         if (holdingsTree != null && holdingsTree.getHoldings() != null) {
517                             holdingsId = holdingsTree.getHoldings().getId();
518                             if (holdingsTree.getHoldings().getHoldingsType().equals(OLEConstants.OleHoldings.ELECTRONIC)) {
519                                 WorkEInstanceOlemlForm eHoldingForm = new WorkEInstanceOlemlForm();
520                                 HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
521                                 eHoldingForm.seteResourceId(editorForm.geteResourceId());
522                                 eHoldingForm.seteResourceTitle(editorForm.geteResourceTitle());
523                                 eHoldingForm.setTokenId(editorForm.getTokenId());
524                                 //getOleEResourceSearchService().getEResourcesFields(eResourceID, holdingsTree.getHoldings().getContentObject(), eHoldingForm);
525                                 holdingsTree.getHoldings().setId(holdingsId);
526                                 holdingsTree.getHoldings().getContentObject().setAccessStatus(OLEConstants.OleHoldings.ACTIVE);
527                                 holdingsTree.getHoldings().setContent(holdingOlemlRecordProcessor.toXML(holdingsTree.getHoldings().getContentObject()));
528                                 docstoreClient.updateHoldings(holdingsTree.getHoldings());
529                             }
530                         }
531                     } catch (Exception e) {
532                         LOG.error("Exception :", e);
533                         StringBuffer marcEditorErrorMessage = new StringBuffer(OLEConstants.MARC_EDITOR_FAILURE)
534                                 .append("\n" + e.getMessage());
535                         GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "docstore.response", marcEditorErrorMessage.toString());
536                     }
537                 }
538                 if (StringUtils.isNotEmpty(bib.getId())) {
539                     Map<String, String> tempId = new HashMap<String, String>();
540                     tempId.put(OLEConstants.BIB_ID, bib.getId());
541                     List<OLEEResourceInstance> oleERSInstances = (List<OLEEResourceInstance>)getBusinessObjectService().findMatching(OLEEResourceInstance.class, tempId);
542                     if (oleERSInstances.size() > 0) {
543                         for (OLEEResourceInstance oleeResourceInstance : oleERSInstances) {
544                             if (oleeResourceInstance.getBibId().equals(bib.getId())) {
545                                 if (StringUtils.isNotEmpty(oleeResourceInstance.getOleERSIdentifier())) {
546                                     Map<String, String> eResId = new HashMap<String, String>();
547                                     eResId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceInstance.getOleERSIdentifier());
548                                     OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument)getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, eResId);
549                                     Person principalPerson = SpringContext.getBean(PersonService.class).getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
550                                     tempDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(tempDocument.getDocumentNumber()));
551                                     tempDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(tempDocument.getDocumentNumber(), principalPerson));
552                                     if (tempDocument != null) {
553                                         try {
554                                             tempDocument.setSelectInstance(OLEConstants.OLEEResourceRecord.CREATE_NEW_INSTANCE);
555                                             tempDocument.seteInstanceFlag(true);
556                                             List<Holdings> holdings = new ArrayList<>();
557                                             tempDocument.setOleERSInstances(getEResourceInstance(oleeResourceInstance.getOleEResourceInstanceId()));
558                                             for (OLEEResourceInstance oleERSInstance : tempDocument.getOleERSInstances()) {
559                                                 if (oleERSInstance.getBibId().equals(bib.getId())) {
560                                                     processResponseForEResource(oleERSInstance.getInstanceId(), bib, tempDocument.getDocumentNumber());
561                                                     holdings.add(docstoreClient.retrieveHoldings(oleERSInstance.getInstanceId()));
562                                                 }
563                                             }
564                                             for(Holdings holdings1:holdings){
565                                                 getOleEResourceSearchService().getNewInstance(tempDocument, tempDocument.getDocumentNumber(), holdings1);
566                                             }
567                                             getBusinessObjectService().save(tempDocument.getOleERSInstances());
568                                             getDocumentService().updateDocument(tempDocument);
569                                         } catch (Exception e) {
570                                             LOG.error("Exception :", e);
571                                             throw new RiceRuntimeException(
572                                                     "Exception trying to save document: " + tempDocument
573                                                             .getDocumentNumber(), e);
574                                         }
575                                     }
576                                 }
577                             }
578                         }
579                     } else {
580                         if (StringUtils.isNotEmpty(eResourceID)) {
581                             Map<String, String> eResId = new HashMap<String, String>();
582                             eResId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceID);
583                             OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, eResId);
584                             Person principalPerson = SpringContext.getBean(PersonService.class).getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
585                             tempDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(tempDocument.getDocumentNumber()));
586                             tempDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(tempDocument.getDocumentNumber(), principalPerson));
587                             if (tempDocument != null) {
588                                 try {
589                                     tempDocument.setSelectInstance(OLEConstants.OLEEResourceRecord.CREATE_NEW_INSTANCE);
590                                     tempDocument.seteInstanceFlag(true);
591                                     processResponseForEResource(holdingsId, bib, tempDocument.getDocumentNumber());
592                                     getOleEResourceSearchService().getNewInstance(tempDocument, tempDocument.getDocumentNumber(), holdingsTree.getHoldings());
593                                     getBusinessObjectService().save(tempDocument.getOleERSInstances());
594                                     getDocumentService().updateDocument(tempDocument);
595                                 } catch (Exception e) {
596                                     LOG.error("Exception :", e);
597                                     throw new RiceRuntimeException(
598                                             "Exception trying to save document: " + tempDocument
599                                                     .getDocumentNumber(), e);
600                                 }
601                             }
602                         }
603                     }
604                 }
605             } catch (Exception e) {
606                 LOG.error("Exception :", e);
607                 StringBuffer marcEditorErrorMessage = new StringBuffer(OLEConstants.MARC_EDITOR_FAILURE)
608                         .append("\n" + e.getMessage());
609                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "record.save.fail.message");
610             }
611         } else {
612 
613             return workBibMarcForm;
614         }
615         workBibMarcForm.setViewId("WorkBibEditorViewPage");
616 
617         WorkBibMarcForm workBibMarcForm1 = (WorkBibMarcForm) loadDocument(editorForm);
618         GlobalVariables.getMessageMap().getInfoMessages().clear();
619         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorStatusMessage);
620         editorForm.setShowClose(true);
621         return workBibMarcForm1;
622     }
623 
624     /**
625      * This method appends the 260 a,b,c values in the workform.
626      * @param workBibMarcForm
627      */
628     private void append260Values(WorkBibMarcForm workBibMarcForm) {
629         for (MarcEditorDataField dataField : workBibMarcForm.getDataFields()) {
630             if (StringUtils.isNotBlank(dataField.getTag()) && dataField.getTag().equalsIgnoreCase(OLEConstants.DATAFIELD_260)) {
631                 StringBuilder value260Builder = new StringBuilder();
632                 if (StringUtils.isNotBlank(dataField.getValue260a()) && !dataField.getValue260a().trim().equalsIgnoreCase(OLEConstants.PIPE + OLEConstants.A)) {
633                     value260Builder.append(dataField.getValue260a() + " ");
634                 }
635                 if (StringUtils.isNotBlank(dataField.getValue260b()) && !dataField.getValue260b().trim().equalsIgnoreCase(OLEConstants.PIPE + OLEConstants.B)) {
636                     value260Builder.append(dataField.getValue260b() + " ");
637                 }
638                 if (StringUtils.isNotBlank(dataField.getValue260c()) && !dataField.getValue260c().trim().equalsIgnoreCase(OLEConstants.PIPE + OLEConstants.C)) {
639                     value260Builder.append(dataField.getValue260c() + " ");
640                 }
641                 if (StringUtils.isBlank(dataField.getValue())) {
642                     dataField.setValue(value260Builder.toString());
643                 }
644             }
645         }
646     }
647 
648     /**
649      * This method removes the empty fields from workform.
650      * @param workBibMarcForm
651      * @return
652      */
653     private List<MarcEditorDataField> removeEmptyDataFields(WorkBibMarcForm workBibMarcForm) {
654         List<MarcEditorDataField> dataFields = workBibMarcForm.getDataFields();
655         List<MarcEditorDataField> emptyDataFieldList = new ArrayList<>();
656         if (!dataFields.isEmpty()) {
657             for (MarcEditorDataField dataField : dataFields) {
658                 if (null != dataField && (StringUtils.isBlank(dataField.getValue()) || dataField.getValue().trim().equalsIgnoreCase(OLEConstants.PIPE + OLEConstants.A))) {
659                     if (StringUtils.isNotBlank(dataField.getTag()) && dataField.getTag().equalsIgnoreCase(OLEConstants.DATAFIELD_245)) {
660                         continue;
661                     }
662                     emptyDataFieldList.add(dataField);
663                 }
664             }
665         }
666         return emptyDataFieldList;
667     }
668     /**
669      * Gets the isNewRecord attribute.
670      * if uuid is null return true else return false.
671      *
672      * @param uuid
673      * @return isNewRecord.
674      */
675     private boolean isNewRecord(String uuid) {
676         return null == uuid;
677     }
678 
679     /**
680      * This method will processResponse,provided the docStore should return response and should have a tokenId
681      *
682      * @param responseFromDocstore
683      * @param editorForm
684      */
685     public void processResponse(String responseFromDocstore, EditorForm editorForm, String uuid) {
686         ResponseHandler responseHandler = new ResponseHandler();
687         Response docStoreResponse = responseHandler.toObject(responseFromDocstore);
688         if (isSuccessfull(docStoreResponse)) {
689             if (responseToOLESentRequired()) {
690                 if (uuid == null || StringUtils.isEmpty(uuid)) {
691                     processNewRecordResponseForOLE(responseFromDocstore);
692                 } else {
693                     processEditRecordResponseForOLE(responseFromDocstore);
694                 }
695             }
696             GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "marc.editor.success.message");
697         } else
698             editorForm.setMessage(docStoreResponse.getMessage());
699     }
700 
701     public void processResponseForEResource(String instanceId, Bib bib, String tokenId) throws Exception {
702         OLEEditorResponse oleEditorResponse = new OLEEditorResponse();
703         oleEditorResponse.setTokenId(tokenId);
704         oleEditorResponse.setLinkedInstanceId(instanceId);
705         oleEditorResponse.setBib(bib);
706         HashMap<String, OLEEditorResponse> oleEditorResponseMap = new HashMap<String, OLEEditorResponse>();
707         oleEditorResponseMap.put(tokenId, oleEditorResponse);
708         OleDocstoreResponse.getInstance().setEditorResponse(oleEditorResponseMap);
709     }
710 
711     public void processResponse(Bib bib, String linkToOrderOption) {
712         OLEEditorResponse oleEditorResponse = new OLEEditorResponse();
713         bib = (Bib) bib.deserializeContent(bib);
714         oleEditorResponse.setBib(bib);
715         oleEditorResponse.setTokenId(tokenId);
716         oleEditorResponse.setLinkToOrderOption(linkToOrderOption);
717         HashMap<String, OLEEditorResponse> oleEditorResponseMap = new HashMap<String, OLEEditorResponse>();
718         oleEditorResponseMap.put(tokenId, oleEditorResponse);
719         OleDocstoreResponse.getInstance().setEditorResponse(oleEditorResponseMap);
720     }
721 
722     /**
723      * The method will process the new record if it receives response form docStore and should have tokenId.
724      *
725      * @param responseFromDocstore
726      */
727     private void processNewRecordResponseForOLE(String responseFromDocstore) {
728         String instanceUUID = null;
729         List bibInfo = null;
730         DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
731         Response responseRecordForDocstore = getResponseRecordForDocstore(responseFromDocstore);
732 
733         OleEditorResponse oleEditorResponse = new OleEditorResponse();
734         OleBibRecord oleBibRecord = new OleBibRecord();
735 
736         instanceUUID = getUUID(responseRecordForDocstore, OLEConstants.INSTANCE_DOC_TYPE);
737         bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
738         if (bibInfo.isEmpty()) {
739             try {
740                 Thread.sleep(3000);
741             } catch (Exception ex) {
742                 LOG.error("Exception :", ex);
743             }
744             bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
745         }
746         oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
747         oleBibRecord.setLinkedInstanceId(instanceUUID);
748         oleBibRecord.setBibUUID(getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE));
749 
750         oleEditorResponse.setOleBibRecord(oleBibRecord);
751         oleEditorResponse.setTokenId(tokenId);
752 
753         OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
754         String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
755 
756 
757         OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean("oleExposedWebService");
758 
759         oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
760     }
761 
762     /**
763      * The method will process the edit record if it receives response form docStore and should have tokenId.
764      *
765      * @param responseFromDocstore
766      */
767     private void processEditRecordResponseForOLE(String responseFromDocstore) {
768         String bibUUID = null;
769         List bibInfo = null;
770         DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
771         Response responseRecordForDocstore = getResponseRecordForDocstore(responseFromDocstore);
772         OleEditorResponse oleEditorResponse = new OleEditorResponse();
773         OleBibRecord oleBibRecord = new OleBibRecord();
774         bibUUID = getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE);
775         bibInfo = discoveryHelperService.getBibInformationFromBibId(bibUUID);
776         oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
777         HashMap instanceIdentifierHashMap = (HashMap) bibInfo.get(0);
778         ArrayList instanceIdentifierList = (ArrayList) instanceIdentifierHashMap.get(OLEConstants.BIB_INSTANCE_ID);
779         String instanceId = (String) instanceIdentifierList.get(0);
780         oleBibRecord.setLinkedInstanceId(instanceId);
781         oleBibRecord.setBibUUID(getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE));
782         oleEditorResponse.setOleBibRecord(oleBibRecord);
783         oleEditorResponse.setTokenId(tokenId);
784         OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
785         String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
786         OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl) SpringContext.getBean("oleExposedWebService");
787         oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
788     }
789 
790 
791     /**
792      * Gets the isSuccessfull attribute
793      *
794      * @param docStoreResponse
795      * @return Returns isSuccessfull
796      */
797     private boolean isSuccessfull(Response docStoreResponse) {
798         return docStoreResponse.getStatus().equalsIgnoreCase(OLEConstants.OLE_DOCSTORE_RESPONSE_STATUS);
799     }
800 
801 
802     /**
803      * This method returns True if tokenId is not null,else return False.
804      *
805      * @return boolean
806      */
807     public boolean responseToOLESentRequired() {
808         return null != tokenId;
809     }
810 
811     /**
812      * This method invokes another method to get uuid based on response and docType.
813      *
814      * @param response
815      * @param docType
816      * @return uuid
817      */
818     private String getUUID(Response response, String docType) {
819         List<ResponseDocument> documents = response.getDocuments();
820         return getUUID(documents, docType);
821     }
822 
823     /**
824      * This method gets the uuid based on the List of responseDocument and docType
825      *
826      * @param documents
827      * @param docType
828      * @return uuid
829      */
830     private String getUUID(List<ResponseDocument> documents, String docType) {
831         for (Iterator<ResponseDocument> iterator = documents.iterator(); iterator.hasNext(); ) {
832             ResponseDocument responseDocument = iterator.next();
833             if (responseDocument.getType().equals(docType)) {
834                 return responseDocument.getUuid();
835             } else {
836                 return getUUID(responseDocument.getLinkedDocuments(), docType);
837             }
838         }
839         return null;
840     }
841 
842 
843     /**
844      * Gets the webservice URL using PropertyUtil.
845      *
846      * @return String
847      */
848     public String getURL() {
849         String url = ConfigContext.getCurrentContextConfig().getProperty("oleExposedWebService.url");
850         return url;
851     }
852 
853     /**
854      * This method returns a response record based on the responseFromDocstore.
855      *
856      * @param responseFromDocstore
857      * @return Response
858      */
859     private Response getResponseRecordForDocstore(String responseFromDocstore) {
860         return new ResponseHandler().toObject(responseFromDocstore);
861     }
862 
863 
864     private void updateTreeData(EditorForm editorForm) {
865         int indexOfDocument = 0;
866        /* List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
867         int i = 0;
868         for (WorkBibDocument bibDocument : workBibDocumentList) {
869             if (editorForm.getDocId().equals(bibDocument.getId())) {
870                 indexOfDocument = i;
871                 break;
872             }
873             i++;
874         }
875         DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
876         WorkBibDocument workBibDocument = new WorkBibDocument();
877         workBibDocument.setId(editorForm.getDocId());
878         workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument);
879         workBibDocumentList.set(indexOfDocument, workBibDocument);
880         editorForm.setWorkBibDocumentList(workBibDocumentList);*/
881 
882         List<Bib> bibList = editorForm.getBibList();
883         int i = 0;
884         for (Bib bib : bibList) {
885             if (editorForm.getDocId().equals(bib.getId())) {
886                 indexOfDocument = i;
887                 break;
888             }
889             i++;
890         }
891         Bib bib = null;
892         try {
893             bib = docstoreClient.retrieveBib(editorForm.getDocId());
894         } catch (Exception e) {
895             LOG.error("Exception :", e);
896             DocstoreException docstoreException = (DocstoreException) e;
897             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
898                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
899             } else {
900                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
901             };
902         }
903         bibList.set(indexOfDocument, bib);
904         editorForm.setBibList(bibList);
905     }
906 
907     /**
908      * This method will Validate the MarcEditorForm and return either True or False
909      * Validation happen based on existence of leader,Tags and values for controlFields and dataFields .
910      *
911      * @param workBibMarcForm
912      * @return valid
913      */
914     public boolean validateMarcEditorData(WorkBibMarcForm workBibMarcForm) {
915         boolean valid;
916         WorkBibMarcRecordValidator wbmRecordValidator = new WorkBibMarcRecordValidator();
917         WorkBibMarcRecord workBibMarcRecord = ConvertMarcFormToMarcRecord(workBibMarcForm);
918         List<DocStoreValidationError> docStoreValidationErrors = wbmRecordValidator.validate(workBibMarcRecord);
919         if (docStoreValidationErrors.size() > 0) {
920             for (DocStoreValidationError docStoreValidationError : docStoreValidationErrors) {
921                 List<String> errorParams = docStoreValidationError.getErrorParams();
922                 String param1 = "";
923                 String param2 = "";
924                 if (errorParams != null) {
925                     if (errorParams.size() == 1) {
926                         param1 = errorParams.get(0);
927                     }
928                     if (errorParams.size() == 2) {
929                         param1 = errorParams.get(0);
930                         param2 = errorParams.get(1);
931                     }
932                 }
933                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,
934                         docStoreValidationError.getErrorId(), param1, param2);
935             }
936             valid = false;
937         } else {
938             valid = true;
939         }
940 
941         return valid;
942     }
943 
944     private WorkBibMarcRecord ConvertMarcFormToMarcRecord(WorkBibMarcForm workBibMarcForm) {
945         WorkBibMarcRecord workBibMarcRecord = new WorkBibMarcRecord();
946         List<ControlField> controlFields = new ArrayList<>();
947         List<DataField> dataFields = new ArrayList<DataField>();
948         for (MarcEditorControlField MEControlFiled : workBibMarcForm.getControlFields()) {
949             ControlField controlField = new ControlField();
950             controlField.setTag(MEControlFiled.getTag());
951             controlField.setValue(MEControlFiled.getValue());
952             controlFields.add(controlField);
953         }
954         for (MarcEditorDataField MEDataField : workBibMarcForm.getDataFields()) {
955             buildDataField(MEDataField, dataFields);
956         }
957         workBibMarcRecord.setLeader(workBibMarcForm.getLeader());
958         workBibMarcRecord.setControlFields(controlFields);
959         workBibMarcRecord.setDataFields(dataFields);
960         return workBibMarcRecord;
961     }
962 
963     private void buildDataField(MarcEditorDataField meDataField, List<DataField> dataFields) {
964         DataField dataField = new DataField();
965         dataField.setTag(meDataField.getTag());
966 
967         if (meDataField.getValue().length() > 1 && !meDataField.getValue().startsWith("|") && !meDataField.getValue().contains("|a")) {
968             meDataField.setValue("|a " + meDataField.getValue());
969         }
970 
971 
972         if (meDataField.getValue().startsWith("|") && meDataField.getValue().length() > 1) {
973             String[] values = meDataField.getValue().split("\\|");
974             for (int i = 1; i < values.length; i++) {
975                 SubField subField = new SubField();
976                 subField.setCode(values[i].substring(0, 1));
977                 subField.setValue(values[i].substring(1, values[i].length()));
978                 dataField.addSubField(subField);
979             }
980         } else {
981             SubField subField = new SubField();
982             subField.setValue(meDataField.getValue());
983             subField.setCode("");
984             dataField.addSubField(subField);
985         }
986 
987         if (meDataField.getInd1() != null && !meDataField.getInd1().isEmpty()) {
988             dataField.setInd1(meDataField.getInd1());
989         } else {
990             dataField.setInd1(" ");
991         }
992 
993         if (meDataField.getInd2() != null && !meDataField.getInd2().isEmpty()) {
994             dataField.setInd2(meDataField.getInd2());
995         } else {
996             dataField.setInd2(" ");
997         }
998         dataFields.add(dataField);
999     }
1000 
1001     private void buildDataFieldList(WorkBibMarcForm workBibMarcForm) {
1002         List<MarcEditorDataField> dataFieldList = workBibMarcForm.getDataFields();
1003         List<MarcEditorDataField> dataFieldList1 = new ArrayList<>();
1004         int count = 0;
1005         if (dataFieldList.size() > 1) {
1006             for (MarcEditorDataField dataField : dataFieldList) {
1007 
1008                 if (dataField.getInd1().equals("") || dataField.getInd1().equals("#") || dataField.getInd1() == null) {
1009                     dataField.setInd1(" ");
1010                 }
1011 
1012                 if (dataField.getInd2().equals("") || dataField.getInd2().equals("#") || dataField.getInd2() == null) {
1013                     dataField.setInd2(" ");
1014                 }
1015 
1016                 if (dataField.getTag().equals("") && dataField.getValue().equals("") && (dataField.getInd1().equals("") || dataField.getInd1().equals(" ") || dataField.getInd1().equals("#") || dataField.getInd1() == null) && (dataField.getInd2().equals("") || dataField.getInd2().equals(" ") || dataField.getInd2().equals("#") || dataField.getInd2() == null)) {
1017                     count++;
1018                 }
1019                 if (!dataField.getTag().equals("") || !dataField.getValue().equals("") || !(dataField.getInd1().equals("") || dataField.getInd1().equals(" ") || dataField.getInd1().equals("#") || dataField.getInd1() == null) || !(dataField.getInd2().equals("") || dataField.getInd2().equals(" ") || dataField.getInd2().equals("#") || dataField.getInd2() == null)) {
1020 
1021                     dataFieldList1.add(dataField);
1022                 }
1023                 if (count == dataFieldList.size()) {
1024                     if (dataField.getTag().equals("") && dataField.getValue().equals("") && (dataField.getInd1().equals("") || dataField.getInd1().equals(" ") || dataField.getInd1().equals("#") || dataField.getInd1() == null) && (dataField.getInd2().equals("") || dataField.getInd2().equals(" ") || dataField.getInd2().equals("#") || dataField.getInd2() == null)) {
1025 
1026                         dataFieldList1.add(dataFieldList.get(0));
1027 
1028                     }
1029                 }
1030 
1031 
1032             }
1033             workBibMarcForm.setDataFields(dataFieldList1);
1034         } else {
1035             workBibMarcForm.setDataFields(dataFieldList);
1036         }
1037 
1038     }
1039 
1040 
1041     private void buildLeader(WorkBibMarcForm workBibMarcForm) {
1042         workBibMarcForm.setLeader(workBibMarcForm.getLeader().replace("#", " "));
1043     }
1044 
1045     @Override
1046     public EditorForm deleteDocument(EditorForm editorForm) {
1047         return new WorkBibMarcForm();
1048     }
1049 
1050     @Override
1051     public String saveDocument(BibTree bibTree, EditorForm form) {
1052         String str = " success";
1053         try {
1054             docstoreClient.updateBib(bibTree.getBib());
1055         } catch (DocstoreException e) {
1056             LOG.error("Exception :", e);
1057             DocstoreException docstoreException = (DocstoreException) e;
1058             if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1059                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1060             } else {
1061                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1062             }
1063         } catch (Exception e) {
1064             LOG.error("Exception ", e);
1065             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
1066         }
1067         return str;
1068     }
1069 
1070     @Override
1071     public EditorForm createNewRecord(EditorForm editorForm, BibTree bibTree) {
1072 //        editorForm.setHeaderText("Import Bib Step-4 Bibliographic Editor - MARC Format");
1073         editorForm.setHeaderText("Import Bib Step-4 Bibliographic Editor");
1074         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
1075 
1076         Bib bib = bibTree.getBib();
1077         if(StringUtils.isEmpty(bib.getCreatedBy())) {
1078             bib.setCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
1079         }
1080         if (bib.getContent() != null) {
1081 
1082             BibMarcRecords bibMarcRecords = bibMarcRecordProcessor.fromXML(bib.getContent());
1083 
1084             List<BibMarcRecord> bibMarcRecordsRecords = bibMarcRecords.getRecords();
1085             for (BibMarcRecord bibMarcRecord : bibMarcRecordsRecords) {
1086                 workBibMarcForm.setLeader(bibMarcRecord.getLeader());
1087                 workBibMarcForm.setControlFields(getMarcFormDataHandler().buildMarcEditorControlFields(workBibMarcForm,
1088                         bibMarcRecord.getControlFields()));
1089                 editorForm.setTitle(getMarcFormDataHandler().buildMarcEditorTitleField(bibMarcRecord.getDataFields())+" / "+ DocumentUniqueIDPrefix.getDocumentId(bib.getId()));
1090                 workBibMarcForm.setDataFields(
1091                         getMarcFormDataHandler().buildMarcEditorDataFields(bibMarcRecord.getDataFields()));
1092                 OleBibliographicRecordStatus bibliographicRecordStatus = null;
1093                 BusinessObjectService boService = getBusinessObjectService();
1094                 String bibStatusName = bib.getStatus();
1095 
1096                 editorForm.setBibStatus(bibStatusName);
1097                 Map parentCriteria = new HashMap();
1098                 parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
1099                 bibliographicRecordStatus = boService
1100                         .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
1101                 if (bibliographicRecordStatus != null) {
1102                     editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
1103                 }
1104                 editorForm.setMessage("Please edit details for the Bib record.");
1105                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_ERRORS, "info.edit.details.bib.record");
1106             }
1107         }
1108 
1109         // Add a node for this document to the left pane tree.
1110         addDocumentToTree(editorForm);
1111         editorForm.setNeedToCreateInstance(true);
1112 
1113         workBibMarcForm.setViewId("WorkBibEditorViewPage");
1114         setControlFields(workBibMarcForm);
1115         return workBibMarcForm;
1116     }
1117 
1118 
1119     public void setControlFields(WorkBibMarcForm workBibMarcForm) {
1120         List<ControlField006Text> controlField006Texts = workBibMarcForm.getMarcControlFields().getControlFields006List();
1121         List<ControlField006Text> controlField006EditText = new ArrayList<>();
1122         for (ControlField006Text controlField006Text : controlField006Texts) {
1123             if (controlField006Text.getRawText() != null) {
1124                 controlField006Text.setRawText(controlField006Text.getRawText().replaceAll(" ", "#"));
1125                 controlField006EditText.add(controlField006Text);
1126             }
1127         }
1128         if (controlField006EditText.size() > 0) {
1129             workBibMarcForm.getMarcControlFields().setControlFields006List(controlField006EditText);
1130         }
1131         List<ControlField007Text> controlField007Texts = workBibMarcForm.getMarcControlFields().getControlFields007List
1132                 ();
1133         List<ControlField007Text> controlField007EditText = new ArrayList<>();
1134         for (ControlField007Text controlField007Text : controlField007Texts) {
1135             if (controlField007Text.getRawText() != null) {
1136                 controlField007Text.setRawText(controlField007Text.getRawText().replaceAll(" ", "#"));
1137                 controlField007EditText.add(controlField007Text);
1138             }
1139         }
1140         if (controlField007EditText.size() > 0) {
1141             workBibMarcForm.getMarcControlFields().setControlFields007List(controlField007EditText);
1142         }
1143         ControlField008 controlField008 = workBibMarcForm.getMarcControlFields().getControlField008();
1144         if (controlField008 != null) {
1145             controlField008.setRawText(controlField008.getRawText().replaceAll(" ", "#"));
1146             workBibMarcForm.getMarcControlFields().setControlField008(controlField008);
1147         }
1148         if (workBibMarcForm.getLeader() != null) {
1149             workBibMarcForm.setLeader(workBibMarcForm.getLeader().replaceAll(" ", "#"));
1150         }
1151     }
1152 
1153     @Override
1154     public EditorForm editNewRecord(EditorForm editorForm, BibTree bibTree) {
1155         WorkBibMarcForm workBibMarcForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1156         if (!validateMarcEditorData(workBibMarcForm)) {
1157             workBibMarcForm.setValidInput(false);
1158             return workBibMarcForm;
1159         }
1160         String bibliographicRecordStatusCode = editorForm.getOleBibliographicRecordStatus()
1161                 .getBibliographicRecordStatusCode();
1162         String content = getMarcFormDataHandler().buildBibRecordForDocStore(workBibMarcForm);
1163         bibTree.getBib().setContent(content);
1164         editorForm.setCreatedBy(bibTree.getBib().getCreatedBy());
1165         editorForm.setCreatedDate(bibTree.getBib().getCreatedOn());
1166         OleBibliographicRecordStatus bibliographicRecordStatus = null;
1167         BusinessObjectService boService = getBusinessObjectService();
1168         if (bibliographicRecordStatusCode != null) {
1169             Map parentCriteria = new HashMap();
1170             parentCriteria.put("bibliographicRecordStatusCode", bibliographicRecordStatusCode);
1171             bibliographicRecordStatus = boService
1172                     .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
1173         }
1174 
1175         if (bibliographicRecordStatus != null) {
1176             bibTree.getBib().setStatus(bibliographicRecordStatus.getBibliographicRecordStatusName());
1177             editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
1178 
1179         } else {
1180             bibTree.getBib().setStatus("");
1181         }
1182         bibTree.getBib().setStaffOnly(editorForm.isStaffOnlyFlagForBib());
1183 
1184         return editorForm;
1185     }
1186 
1187     private void addDocumentToTree(EditorForm editorForm) {
1188         // TODO: Make sure the same document is not added more than once.
1189 
1190         List<BibTree> bibTreeList = editorForm.getBibTreeList();
1191         List<Bib> bibList = new ArrayList<>();
1192         int indexOfDocument = 0;
1193         int i = 0;
1194         String title = "New Bib1";
1195         boolean updateTitle = false;
1196         if (null == bibTreeList) {
1197             bibTreeList = new ArrayList<BibTree>();
1198         }
1199         BibTree tempBibTree = new BibTree();
1200         if (null == editorForm.getDocId()) {
1201             LOG.info("bibTreeList size before remove-->" + bibTreeList.size());
1202             for (BibTree bibTree : bibTreeList) {
1203                 if (bibTree.getBib().getTitle().equalsIgnoreCase("New Bib1")) {
1204                     tempBibTree = bibTree;
1205                     // workBibDocumentList.remove(workBibDocument);
1206                 }
1207             }
1208             bibTreeList.remove(tempBibTree);
1209             LOG.info("workBibDocumentList size after remove-->" + bibTreeList.size());
1210 
1211             BibTree bibTree = new BibTree();
1212             Bib bib = new Bib();
1213             bib.setTitle(title);
1214             bibTree.setBib(bib);
1215             /*bibTree.getBib().setTitle(title);*/
1216             bibTreeList.add(bibTree);
1217         } else {
1218             boolean isUpdated = false;
1219             for (BibTree bibTree : bibTreeList) {
1220                 if (bibTree.getBib() != null) {
1221                     if (bibTree.getBib().getId() != null && bibTree.getBib().getId().equals(editorForm.getDocId())) {
1222                         isUpdated = true;
1223                         break;
1224                     } else if (bibTree.getBib().getTitle().equals(title)) {
1225                         indexOfDocument = i;
1226                         updateTitle = true;
1227                         break;
1228                     }
1229                 }
1230                 i++;
1231             }
1232             if (!isUpdated) {
1233                 Bib bib = null;
1234                 try {
1235                     bib = docstoreClient.retrieveBib(editorForm.getDocId());
1236                 } catch (Exception e) {
1237                     LOG.error("Exception :", e);
1238                     DocstoreException docstoreException = (DocstoreException) e;
1239                     if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1240                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1241                     } else {
1242                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1243                     }
1244                 }
1245                 if (updateTitle && bibList.size() > 0) {
1246                     bibList.set(indexOfDocument, bib);
1247                 } else {
1248                     bibList.add(bib);
1249                 }
1250 
1251             }
1252 
1253         }
1254         editorForm.setBibTreeList(bibTreeList);
1255     }
1256 
1257     @Override
1258     public EditorForm addORDeleteFields(EditorForm editorForm, HttpServletRequest request) {
1259 
1260         String methodName = request.getParameter("methodToCall");
1261         if (methodName.equalsIgnoreCase("addControlField006")) {
1262             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1263             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1264             index++;
1265             List<ControlField006Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields006List();
1266             marcEditorControlFieldList.add(index, new ControlField006Text());
1267             marcEditorForm.getMarcControlFields().setControlFields006List(marcEditorControlFieldList);
1268             editorForm.setDocumentForm(marcEditorForm);
1269         } else if (methodName.equalsIgnoreCase("removeControlField006")) {
1270             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1271             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1272             List<ControlField006Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields006List();
1273             if (marcEditorControlFieldList.size() > 1) {
1274                 marcEditorControlFieldList.remove(index);
1275             }
1276             editorForm.setDocumentForm(marcEditorForm);
1277         } else if (methodName.equalsIgnoreCase("addControlField007")) {
1278             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1279             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1280             index++;
1281             List<ControlField007Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields007List();
1282             marcEditorControlFieldList.add(index, new ControlField007Text());
1283             marcEditorForm.getMarcControlFields().setControlFields007List(marcEditorControlFieldList);
1284             editorForm.setDocumentForm(marcEditorForm);
1285         } else if (methodName.equalsIgnoreCase("removeControlField007")) {
1286             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1287             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1288             List<ControlField007Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields007List();
1289             if (marcEditorControlFieldList.size() > 1) {
1290                 marcEditorControlFieldList.remove(index);
1291             }
1292             editorForm.setDocumentForm(marcEditorForm);
1293         } else if (methodName.equalsIgnoreCase("addDataField")) {
1294             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1295             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1296             index++;
1297             List<MarcEditorDataField> editorDataFieldList = marcEditorForm.getDataFields();
1298             for (MarcEditorDataField editorDataField : editorDataFieldList) {
1299                 if (null != editorDataField.getValue()) {
1300                     String modifiedValue = editorDataField.getValue().replace("\"", "&quot;");
1301                     editorDataField.setValue(modifiedValue);
1302                 }
1303             }
1304             MarcEditorDataField marcEditorDataField = new MarcEditorDataField();
1305             if (editorForm.isShortcutAddDataField()) {
1306                 marcEditorDataField.setTag("035");
1307                 marcEditorDataField.setValue("(OCoLC)");
1308                 editorForm.setShortcutAddDataField(false);
1309             }
1310             editorDataFieldList.add(index, marcEditorDataField);
1311             marcEditorForm.setDataFields(editorDataFieldList);
1312             editorForm.setDocumentForm(marcEditorForm);
1313         } else if (methodName.equalsIgnoreCase("removeDataField")) {
1314             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1315             List<MarcEditorDataField> marcEditorDataFieldList = marcEditorForm.getDataFields();
1316             List<MarcEditorDataField> removeEditorDataFieldList = new ArrayList<>();
1317             if (marcEditorDataFieldList.size() > 1) {
1318                 for (MarcEditorDataField marcEditorDataField : marcEditorDataFieldList) {
1319                     if (marcEditorDataField.isSelected()) {
1320                         removeEditorDataFieldList.add(marcEditorDataField);
1321                     }
1322                 }
1323                 marcEditorDataFieldList.removeAll(removeEditorDataFieldList);
1324             }
1325             for (MarcEditorDataField marcDataField : marcEditorDataFieldList) {
1326                 String modifiedValue = marcDataField.getValue().replace("\"", "&quot;");
1327                 marcDataField.setValue(modifiedValue);
1328             }
1329             if (CollectionUtils.isEmpty(marcEditorDataFieldList)) {
1330                 marcEditorDataFieldList.add(new MarcEditorDataField());
1331             }
1332             marcEditorForm.setDataFields(marcEditorDataFieldList);
1333             editorForm.setDocumentForm(marcEditorForm);
1334         }
1335         return editorForm;
1336     }
1337 
1338     /**
1339      * Gets the MarcEditorFormDataHandler attribute.
1340      *
1341      * @return MarcEditorFormDataHandler
1342      */
1343     private MarcEditorFormDataHandler getMarcFormDataHandler() {
1344         if (null == marcEditorFormDataHandler) {
1345             marcEditorFormDataHandler = new MarcEditorFormDataHandler();
1346         }
1347         return marcEditorFormDataHandler;
1348     }
1349 
1350 
1351     @Override
1352     public EditorForm deleteVerify(EditorForm editorForm) throws Exception {
1353         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
1354         String docId = editorForm.getDocId();
1355         editorForm.setShowDeleteTree(true);
1356         List<String> uuidList = new ArrayList<>(0);
1357         uuidList.add(editorForm.getDocId());
1358         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1359         Node<DocumentTreeNode, String> docTree = documentSelectionTree.add(uuidList, DocType.BIB.getDescription());
1360         editorForm.getDocTree().setRootElement(docTree);
1361         workBibMarcForm.setViewId("DeleteViewPage");
1362         int holdingsCount = 0;
1363         int itemCount = 0;
1364         BibTree bibTree = docstoreClient.retrieveBibTree(docId);
1365         List<HoldingsTree> holdingsTrees = bibTree.getHoldingsTrees();
1366         holdingsCount = holdingsTrees.size();
1367         for(HoldingsTree holdingsTree : holdingsTrees){
1368             int size = holdingsTree.getItems().size();
1369             itemCount = itemCount + size;
1370         }
1371         StringBuffer deleteMessage = new StringBuffer();
1372         deleteMessage.append("WARNING : All attached holdings (");
1373         deleteMessage.append(holdingsCount +")");
1374         deleteMessage.append(" and  items (");
1375         deleteMessage.append(itemCount + ") on the following bibliographic record will be deleted.");
1376         editorForm.setDeleteMessage(deleteMessage.toString());
1377         return workBibMarcForm;
1378     }
1379 
1380 
1381     private Node<DocumentTreeNode, String> buildDocSelectionTree(String responseXml) throws SolrServerException {
1382         Response response = new ResponseHandler().toObject(responseXml);
1383         List<ResponseDocument> responseDocumentList = response.getDocuments();
1384         List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
1385         List<WorkBibDocument> bibDocumentList = new ArrayList<WorkBibDocument>();
1386         List<WorkInstanceDocument> instanceDocumentList = new ArrayList<WorkInstanceDocument>();
1387         WorkHoldingsDocument workHoldingsDocument = null;
1388         WorkInstanceDocument workInstanceDocument = null;
1389         WorkBibDocument workBibDocument = null;
1390         WorkItemDocument workItemDocument = null;
1391         List<String> uuidList = new ArrayList<String>();
1392         String docType = null;
1393         for (ResponseDocument responseDocument : responseDocumentList) {
1394 
1395             if (responseDocument.getType().equalsIgnoreCase(DocType.ITEM.getCode())) {
1396                 workItemDocument = new WorkItemDocument();
1397                 workItemDocument.setItemIdentifier(responseDocument.getUuid());
1398                 uuidList.add(responseDocument.getUuid());
1399                 docType = responseDocument.getType();
1400                 workItemDocumentList.add(workItemDocument);
1401             } else if (responseDocument.getType().equalsIgnoreCase(DocType.HOLDINGS.getCode())) {
1402                 workHoldingsDocument = new WorkHoldingsDocument();
1403                 docType = responseDocument.getType();
1404                 workHoldingsDocument.setHoldingsIdentifier(responseDocument.getUuid());
1405                 uuidList.add(responseDocument.getUuid());
1406             } else if (responseDocument.getType().equalsIgnoreCase(DocType.BIB.getDescription())) {
1407                 workBibDocument = new WorkBibDocument();
1408                 uuidList.add(responseDocument.getUuid());
1409                 workBibDocument.setId(responseDocument.getUuid());
1410                 docType = responseDocument.getType();
1411                 bibDocumentList.add(workBibDocument);
1412             } else if (responseDocument.getType().equalsIgnoreCase(DocType.INSTANCE.getCode())) {
1413                 workInstanceDocument = new WorkInstanceDocument();
1414                 workInstanceDocument.setInstanceIdentifier(responseDocument.getUuid());
1415                 uuidList.add(responseDocument.getUuid());
1416                 docType = responseDocument.getType();
1417                 instanceDocumentList.add(workInstanceDocument);
1418             }
1419         }
1420         if (workItemDocumentList.size() > 0) {
1421             if (workInstanceDocument != null) {
1422                 workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
1423                 workInstanceDocument.setItemDocumentList(workItemDocumentList);
1424             }
1425         }
1426         if (instanceDocumentList.size() > 0) {
1427             if (workBibDocument != null) {
1428                 workBibDocument.setWorkInstanceDocumentList(instanceDocumentList);
1429             }
1430         }
1431         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1432         Node<DocumentTreeNode, String> rootNode = documentSelectionTree.add(uuidList, docType);
1433         return rootNode;
1434     }
1435 
1436     /**
1437      * This method deletes the bib record from docstore by the doc id.
1438      * @param editorForm
1439      * @return
1440      * @throws Exception
1441      */
1442     @Override
1443     public EditorForm delete(EditorForm editorForm) throws Exception {
1444         return deleteFromDocStore(editorForm);
1445     }
1446 
1447     @Override
1448     public EditorForm addORRemoveExtentOfOwnership(EditorForm editorForm, HttpServletRequest request) {
1449         return null;  //To change body of implemented methods use File | Settings | File Templates.
1450     }
1451 
1452     @Override
1453     public EditorForm addORRemoveAccessInformationAndHoldingsNotes(EditorForm editorForm, HttpServletRequest request) {
1454         return null;  //To change body of implemented methods use File | Settings | File Templates.
1455     }
1456 
1457     @Override
1458     public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1459         return null;  //To change body of implemented methods use File | Settings | File Templates.
1460     }
1461 
1462     /**
1463      * Set tag and value for Control field
1464      *
1465      * @param tag
1466      * @param value
1467      * @return
1468      */
1469     private MarcEditorControlField getMarcEditorControlField(String tag, String value) {
1470         MarcEditorControlField marcEditorControlField = new MarcEditorControlField();
1471         marcEditorControlField.setTag(tag);
1472         marcEditorControlField.setValue(value);
1473         return marcEditorControlField;
1474     }
1475 
1476     /**
1477      * Build controlField list with tag and value pairs.
1478      *
1479      * @param workBibMarcForm
1480      */
1481     private void buildControlFieldList(WorkBibMarcForm workBibMarcForm) {
1482         ControlFields controlFields = workBibMarcForm.getMarcControlFields();
1483 
1484         Date dt = new Date();
1485         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss.S");
1486         controlFields.setControlField005(sdf.format(dt).substring(0, 16));
1487 
1488         List<MarcEditorControlField> marcEditorControlFields = new ArrayList<MarcEditorControlField>();
1489         if (StringUtils.isNotEmpty(controlFields.getControlField001())) {
1490             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_001,
1491                     controlFields.getControlField001()));
1492         }
1493         if (StringUtils.isNotEmpty(controlFields.getControlField003())) {
1494             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_003,
1495                     controlFields.getControlField003()));
1496         }
1497         if (StringUtils.isNotEmpty(controlFields.getControlField005())) {
1498             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_005,
1499                     controlFields.getControlField005()));
1500         }
1501         if (controlFields.getControlFields006List().size() > 0) {
1502             for (ControlField006Text controlField006Text : controlFields.getControlFields006List()) {
1503                 if (controlField006Text.getRawText() != null && StringUtils.isNotEmpty(controlField006Text.getRawText()))
1504                     marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_006,
1505                             controlField006Text.getRawText().replace("#", " ")));
1506             }
1507         }
1508         if (controlFields.getControlFields007List().size() > 0) {
1509             for (ControlField007Text controlField007Text : controlFields.getControlFields007List()) {
1510                 if (controlField007Text.getRawText() != null && StringUtils.isNotEmpty(controlField007Text.getRawText()))
1511                     marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_007,
1512                             controlField007Text.getRawText().replace("#", " ")));
1513             }
1514         }
1515         if (StringUtils.isNotEmpty(controlFields.getControlField008().getRawText())) {
1516             sdf = new SimpleDateFormat("yyMMdd");
1517             if (controlFields.getControlField008().getRawText().length() == 40 && (controlFields.getControlField008().getRawText().substring(0, 6).contains("#") || workBibMarcForm.isCopyFlag())) {
1518                 controlFields.getControlField008().setRawText(sdf.format(dt) + controlFields.getControlField008().getRawText
1519                         ().substring(6, 40));
1520             }
1521 
1522             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_008,
1523                     controlFields.getControlField008().getRawText().replace("#", " ")));
1524         }
1525         workBibMarcForm.setControlFields(marcEditorControlFields);
1526     }
1527 
1528     @Override
1529     public EditorForm showBibs(EditorForm editorForm) {
1530         return null;
1531     }
1532 
1533     public EditorForm copy(EditorForm editorForm) {
1534         editorForm.setDocId(null);
1535         editorForm.setBibId(null);
1536 
1537         WorkBibMarcForm workBibMarcForm = (WorkBibMarcForm) editorForm.getDocumentForm();
1538         workBibMarcForm.getMarcControlFields().setLocalId(null);
1539         workBibMarcForm.getMarcControlFields().setControlField001(null);
1540         workBibMarcForm.getMarcControlFields().setControlField003(null);
1541         workBibMarcForm.setDocId(null);
1542         editorForm.setOleBibliographicRecordStatus(new OleBibliographicRecordStatus());
1543 
1544         eliminate9xxFields(workBibMarcForm);
1545 
1546         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, OLEConstants.MARC_EDITOR_BIB_COPY_MESSAGE);
1547         return editorForm;
1548     }
1549 
1550     /**
1551      * This method eliminates 9xx fields if any.
1552      * @param workBibMarcForm
1553      */
1554     private void eliminate9xxFields(WorkBibMarcForm workBibMarcForm) {
1555         List<MarcEditorDataField> dataFields = workBibMarcForm.getDataFields();
1556         List<MarcEditorDataField> newDataFields = new ArrayList<>();
1557         for (MarcEditorDataField dataField : dataFields) {
1558             if (null != dataField.getTag()) {
1559                 if (!dataField.getTag().startsWith("9")) {
1560                     newDataFields.add(dataField);
1561                 }
1562             }
1563         }
1564         workBibMarcForm.setDataFields(newDataFields);
1565     }
1566 
1567     @Override
1568     public Boolean isValidUpdate(EditorForm editorForm) {
1569         String docId = editorForm.getDocId();
1570         Boolean isValidUpdate = true;
1571         if (StringUtils.isNotEmpty(docId)) {
1572             try {
1573                 if (editorForm.getDocType().equalsIgnoreCase("bibliographic")) {
1574                     Bib bib = docstoreClient.retrieveBib(editorForm.getDocId());
1575                     if (bib.getUpdatedOn() != null) {
1576                         if (editorForm.getUpdatedDate() == null) {
1577                             isValidUpdate = false;
1578                         }
1579                     }
1580                     if (!editorForm.getUpdatedDate().equals(bib.getUpdatedOn())) {
1581                         isValidUpdate = false;
1582                     }
1583                 }
1584                 if (editorForm.getDocType().equalsIgnoreCase("holdings")) {
1585                     Holdings holdings = docstoreClient.retrieveHoldings(editorForm.getDocId());
1586                     if (editorForm.getUpdatedDate().equals(holdings.getUpdatedOn())) {
1587                         isValidUpdate = false;
1588                     }
1589 
1590                 }
1591                 if (editorForm.getDocType().equalsIgnoreCase("item")) {
1592                     Item item = docstoreClient.retrieveItem(editorForm.getDocId());
1593                     if (editorForm.getUpdatedDate().equals(item.getUpdatedOn())) {
1594                         isValidUpdate = false;
1595                     }
1596 
1597                 }
1598             } catch (Exception e) {
1599                 LOG.error("New Record....." + docId);
1600             }
1601         }
1602         return isValidUpdate;
1603     }
1604 
1605     public  List<OLEEResourceInstance> getEResourceInstance(String oleERSIdentifier) {
1606         List<OLEEResourceInstance> oleeResourceInstances = new ArrayList<>();
1607         if (oleERSIdentifier != null) {
1608             Map ids = new HashMap();
1609             ids.put("oleEResourceInstanceId", oleERSIdentifier);
1610             OLEEResourceInstance oleeResourceInstance = (OLEEResourceInstance) getBusinessObjectService().findByPrimaryKey(OLEEResourceInstance.class, ids);
1611             oleeResourceInstances.add(oleeResourceInstance);
1612         }
1613         return oleeResourceInstances;
1614     }
1615 
1616 }