View Javadoc

1   package org.kuali.ole.describe.controller;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.apache.log4j.Logger;
5   import org.apache.solr.client.solrj.SolrServerException;
6   import org.kuali.ole.BibliographicRecordHandler;
7   import org.kuali.ole.OLEConstants;
8   import org.kuali.ole.OleEditorResponseHandler;
9   import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
10  import org.kuali.ole.deliver.bo.OleLoanDocument;
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.service.DiscoveryHelperService;
24  import org.kuali.ole.describe.service.DocstoreHelperService;
25  import org.kuali.ole.docstore.model.bo.WorkBibDocument;
26  import org.kuali.ole.docstore.model.bo.WorkHoldingsDocument;
27  import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
28  import org.kuali.ole.docstore.model.bo.WorkItemDocument;
29  import org.kuali.ole.docstore.model.enums.DocType;
30  import org.kuali.ole.docstore.model.xmlpojo.ingest.AdditionalAttributes;
31  import org.kuali.ole.docstore.model.xmlpojo.ingest.Request;
32  import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument;
33  import org.kuali.ole.docstore.model.xmlpojo.ingest.Response;
34  import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument;
35  import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
36  import org.kuali.ole.pojo.OleBibRecord;
37  import org.kuali.ole.pojo.OleEditorResponse;
38  import org.kuali.ole.pojo.bib.BibliographicRecord;
39  import org.kuali.ole.pojo.bib.Collection;
40  import org.kuali.ole.select.businessobject.OleCopy;
41  import org.kuali.ole.select.service.impl.OleExposedWebServiceImpl;
42  import org.kuali.ole.sys.context.SpringContext;
43  import org.kuali.rice.core.api.config.property.ConfigContext;
44  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
45  import org.kuali.rice.core.api.util.tree.Node;
46  import org.kuali.rice.kim.api.permission.PermissionService;
47  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
48  import org.kuali.rice.krad.service.BusinessObjectService;
49  import org.kuali.rice.krad.service.KRADServiceLocator;
50  import org.kuali.rice.krad.uif.UifParameters;
51  import org.kuali.rice.krad.util.GlobalVariables;
52  import org.kuali.rice.krad.util.KRADConstants;
53  import org.kuali.rice.krad.web.form.UifFormBase;
54  import org.springframework.validation.BindingResult;
55  import org.springframework.web.bind.annotation.ModelAttribute;
56  import org.springframework.web.bind.annotation.RequestMapping;
57  import org.springframework.web.servlet.ModelAndView;
58  
59  import javax.servlet.http.HttpServletRequest;
60  import javax.servlet.http.HttpServletResponse;
61  import java.text.SimpleDateFormat;
62  import java.util.ArrayList;
63  import java.util.Arrays;
64  import java.util.Date;
65  import java.util.HashMap;
66  import java.util.Iterator;
67  import java.util.List;
68  import java.util.Map;
69  
70  /**
71   * Class for handling all editor operations for WorkBibMarc documents.
72   */
73  public class WorkBibMarcEditor extends AbstractEditor implements
74          DocumentEditor {
75  
76      private static final Logger LOG = Logger.getLogger(WorkBibMarcEditor.class);
77  
78      private DocstoreHelperService docstoreHelperService;
79      private MarcEditorFormDataHandler marcEditorFormDataHandler;
80      private String tokenId;
81  
82      private static WorkBibMarcEditor workBibMarcEditor = new WorkBibMarcEditor();
83      private final AbstractEditor abstractEditor = new AbstractEditor();
84  
85      public static WorkBibMarcEditor getInstance() {
86          return workBibMarcEditor;
87      }
88  
89      private WorkBibMarcEditor() {
90      }
91  
92      private boolean  canEditBib(String principalId){
93          PermissionService service= KimApiServiceLocator.getPermissionService();
94          return  service.hasPermission(principalId,OLEConstants.CAT_NAMESPACE,OLEConstants.MARC_EDITOR_EDIT_BIB);
95      }
96  
97      private boolean  canAddBib(String principalId){
98          PermissionService service= KimApiServiceLocator.getPermissionService();
99          return  service.hasPermission(principalId,OLEConstants.CAT_NAMESPACE,OLEConstants.MARC_EDITOR_ADD_BIB);
100     }
101 
102     @Override
103     public EditorForm loadDocument(EditorForm editorForm) {
104         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
105         String docId = editorForm.getDocId();
106         //Modified title display for left pane
107         editorForm.setHasLink(false);
108         workBibMarcForm.setHideFooter(true);
109         editorForm.setHeaderText("Bibliographic Editor - MARC Format");
110         if (null != docId) {
111             try {
112                 // Read the document details from docstore.
113                 // String docStoreData = getDocstoreHelperService().getDocstoreData(docId);
114                 ResponseDocument responseDocument = getDocstoreHelperService().checkOutDocument(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), docId);
115                 Collection bibliographicRecords = new BibliographicRecordHandler()
116                         .fromXML(responseDocument.getContent().getContent());
117                 AdditionalAttributes additionalAttributes = responseDocument.getAdditionalAttributes();
118                 String bibStatusName = additionalAttributes.getAttribute(AdditionalAttributes.STATUS);
119                 editorForm.setCreatedBy(additionalAttributes.getAttribute(AdditionalAttributes.CREATED_BY));
120                 editorForm.setCreatedDate(additionalAttributes.getAttribute(AdditionalAttributes.DATE_ENTERED));
121                 editorForm.setUpdatedBy(additionalAttributes.getAttribute(AdditionalAttributes.UPDATED_BY));
122                 editorForm.setUpdatedDate(additionalAttributes.getAttribute(AdditionalAttributes.LAST_UPDATED));
123                 editorForm.setStatusUpdatedBy(additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_BY));
124                 editorForm.setStatusUpdatedOn(additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_ON));
125                 editorForm.setStaffOnlyFlagForBib(Boolean.valueOf(additionalAttributes.getAttribute(AdditionalAttributes.STAFFONLYFLAG)));
126                 List<BibliographicRecord> bibliographicRecordList = bibliographicRecords.getRecords();
127                 BibliographicRecord bibliographicRecord = bibliographicRecordList.get(0);
128                 editorForm.setTitle(getMarcFormDataHandler().buildMarcEditorTitleField(bibliographicRecord.getDatafields()));
129                 workBibMarcForm.setLeader(bibliographicRecord.getLeader());
130                 workBibMarcForm.setControlFields(
131                         getMarcFormDataHandler().buildMarcEditorControlFields(workBibMarcForm, bibliographicRecord.getControlfields()));
132                 List<MarcEditorDataField> marcEditorDataFields = new ArrayList<MarcEditorDataField>();
133                 marcEditorDataFields =  getMarcFormDataHandler().buildMarcEditorDataFields(bibliographicRecord.getDatafields());
134                 if(!editorForm.getEditable().equalsIgnoreCase("true")){
135                     for(MarcEditorDataField marcEditorDataField :marcEditorDataFields ) {
136                         String tempValue = null;
137                         if(marcEditorDataField.getValue()!=null){
138                             tempValue = marcEditorDataField.getValue().replace("&quot;", "\"");
139                             tempValue = tempValue.replaceAll("&nbsp;", " ");
140                             marcEditorDataField.setValue(tempValue);
141                         }
142                     }
143                 }
144                 workBibMarcForm.setDataFields(marcEditorDataFields);
145                 BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
146                 Map parentCriteria = new HashMap();
147                 parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
148                 OleBibliographicRecordStatus bibliographicRecordStatus = boService
149                         .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
150                 editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
151                 //workBibMarcForm.setMessage("Please edit details for the Bib record.");
152                 if(editorForm.getEditable().equalsIgnoreCase("true")) {
153                     boolean hasEditPermission = canEditBib(GlobalVariables.getUserSession().getPrincipalId());
154                     if(!hasEditPermission) {
155                         editorForm.setHideFooter(false);
156                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_BIB_EDIT_AUTHORIZATION);
157                     }
158                     else {
159                         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.record");
160                     }
161                 }else {
162                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.record");
163                 }
164             } catch (Exception e) {
165                 String message = "Error: Could not load Bib record for id:" + docId;
166                 LOG.error(message, e);
167                 //workBibMarcForm.setMessage(message + "Exception:" + e.getMessage());
168                 GlobalVariables.getMessageMap()
169                         .putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "docstore.response",
170                                 message + "Exception:" + e.getMessage());
171             }
172         } else {
173             //workBibMarcForm.setMessage("Please enter details for new Bib record.");
174             boolean hasAddPermission= canAddBib(GlobalVariables.getUserSession().getPrincipalId());
175             if(!hasAddPermission) {
176                 workBibMarcForm.setEditable("false");
177                 editorForm.setHideFooter(false);
178                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_BIB_CREATE_AUTHORIZATION);
179             }else {
180                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "info.edit.details.bib.new.record");
181             }
182 
183         }
184         // Add a node for this document to the left pane tree.
185         addDocumentToTree(editorForm);
186         setControlFields(workBibMarcForm);
187         workBibMarcForm.setViewId("WorkBibEditorViewPage");
188         return workBibMarcForm;
189     }
190 
191     @Override
192     public EditorForm saveDocument(EditorForm editorForm) {
193 
194         String responseFromDocstore = null;
195         String editorStatusMessage = "";
196         WorkBibMarcForm workBibMarcForm = (WorkBibMarcForm) editorForm.getDocumentForm();
197         String bibliographicRecordStatusCode = editorForm.getOleBibliographicRecordStatus()
198                 .getBibliographicRecordStatusCode();
199         boolean staffOnlyFlag=editorForm.isStaffOnlyFlagForBib();
200         tokenId = editorForm.getTokenId();
201         buildControlFieldList(workBibMarcForm);
202         boolean valid = validateMarcEditorData(workBibMarcForm);
203         buildDataFieldList(workBibMarcForm);
204         buildLeader(workBibMarcForm);
205         Date date = new Date();
206         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
207         String dateStr = sdf.format(date);
208         String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
209         AdditionalAttributes additionalAttributes = new AdditionalAttributes();
210         BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
211         OleBibliographicRecordStatus bibliographicRecordStatus = null;
212         if (bibliographicRecordStatusCode != null) {
213             Map parentCriteria = new HashMap();
214             parentCriteria.put("bibliographicRecordStatusCode", bibliographicRecordStatusCode);
215             bibliographicRecordStatus = boService.findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
216         }
217         if (valid) {
218             MarcEditorFormDataHandler marcEditorFormDataHandler = getMarcFormDataHandler();
219             String content = marcEditorFormDataHandler.buildBibRecordForDocStore(workBibMarcForm);
220 //            String uuid = marcEditorFormDataHandler.getUUIDFromForm(workBibMarcForm);
221             String uuid = editorForm.getDocId();
222             ResponseDocument responseDocument = null;
223 
224             try {
225                 if (null != uuid && !uuid.trim().equals("")) {
226                     if (boService != null) {
227                         responseDocument = getDocstoreHelperService().checkOutDocument(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), uuid);
228                         additionalAttributes = responseDocument.getAdditionalAttributes();
229                         //The following lines are commented as these are handled in Docstore code
230                         //additionalAttributes.setAttribute("lastUpdated", dateStr);
231                         //additionalAttributes.setAttribute("updatedBy", user);
232                         if (bibliographicRecordStatus != null) {
233                             additionalAttributes.setAttribute(AdditionalAttributes.STATUS, bibliographicRecordStatus
234                                     .getBibliographicRecordStatusName());
235                         } else {
236                             additionalAttributes.setAttribute(AdditionalAttributes.STATUS, "");
237                         }
238                     }
239                     additionalAttributes.setAttribute(AdditionalAttributes.STAFFONLYFLAG,String.valueOf(staffOnlyFlag));
240                     responseFromDocstore = getDocstoreHelperService()
241                             .persistToDocstoreWithAdditionalAttributesForEditor(content, additionalAttributes, uuid,
242                                     OLEConstants.MARC_FORMAT);
243                     Response response = new ResponseHandler().toObject(responseFromDocstore);
244                     responseDocument = response.getDocuments().get(0);
245                     additionalAttributes = responseDocument.getAdditionalAttributes();
246                     String bibStatusName = additionalAttributes.getAttribute(AdditionalAttributes.STATUS);
247                     editorForm.setCreatedBy(additionalAttributes.getAttribute(AdditionalAttributes.CREATED_BY));
248                     editorForm.setCreatedDate(additionalAttributes.getAttribute(AdditionalAttributes.DATE_ENTERED));
249                     editorForm.setUpdatedBy(additionalAttributes.getAttribute(AdditionalAttributes.UPDATED_BY));
250                     editorForm.setUpdatedDate(additionalAttributes.getAttribute(AdditionalAttributes.LAST_UPDATED));
251                     editorForm.setStatusUpdatedBy(
252                             additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_BY));
253                     editorForm.setStatusUpdatedOn(
254                             additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_ON));
255                     Map parentCriteria = new HashMap();
256                     parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
257                     bibliographicRecordStatus = boService
258                             .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
259                     if (bibliographicRecordStatus != null) {
260                         editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
261                     }
262                     processResponse(responseFromDocstore, workBibMarcForm, uuid);
263                     if (responseFromDocstore.contains("Success")) {
264                         updateTreeData(editorForm);
265                         //editorForm.setMessage("Record updated successfully");
266                         editorStatusMessage = "Record updated successfully";
267                         editorStatusMessage = "record.update.message";
268 
269                     }
270                 } else {
271                     // The following lines are commented as these are handled in Docstore code
272                     //additionalAttributes.setAttribute("dateEntered", dateStr);
273                     // additionalAttributes.setAttribute("createdBy", user);
274                     additionalAttributes.setAttribute(AdditionalAttributes.STAFFONLYFLAG,String.valueOf(staffOnlyFlag));
275                     if (bibliographicRecordStatus != null) {
276                         additionalAttributes.setAttribute(AdditionalAttributes.STATUS,
277                                 bibliographicRecordStatus.getBibliographicRecordStatusName());
278                     } else {
279                         additionalAttributes.setAttribute(AdditionalAttributes.STATUS, "");
280                     }
281                     /*responseFromDocstore = getDocstoreHelperService()
282                             .persistToDocstoreWithAdditionalAttributesForEditor(content, additionalAttributes, uuid,
283                                                                                 OLEConstants.MARC_FORMAT);*/
284                     try {
285                         if (!isNewRecord(uuid) && !uuid.trim().equals("")) {
286                             responseFromDocstore = getDocstoreHelperService()
287                                     .persistToDocstoreWithAdditionalAttributesForEditor(content, additionalAttributes,
288                                             uuid, OLEConstants.MARC_FORMAT);
289                             processResponse(responseFromDocstore, workBibMarcForm, uuid);
290                         } else {
291                             responseFromDocstore = getDocstoreHelperService()
292                                     .persistToDocstoreWithAdditionalAttributesForEditor(content, additionalAttributes,
293                                             null, OLEConstants.MARC_FORMAT);
294                             processResponse(responseFromDocstore, workBibMarcForm, uuid);
295                         }
296                         workBibMarcForm.setLeader("");
297                         workBibMarcForm.setControlFields(Arrays.asList(new MarcEditorControlField()));
298                         workBibMarcForm.setDataFields(Arrays.asList(new MarcEditorDataField()));
299                         workBibMarcForm.setUuid("");
300 
301                     } catch (Exception e) {
302                         StringBuffer marcEditorErrorMessage = new StringBuffer(OLEConstants.MARC_EDITOR_FAILURE)
303                                 .append("\n" + e.getMessage());
304                         //workBibMarcForm.setMessage(marcEditorErrorMessage.toString());
305                         GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "docstore.response",marcEditorErrorMessage.toString());
306                     }
307                     Response response = new ResponseHandler().toObject(responseFromDocstore);
308                     String marcUUID = response.getDocuments().get(0).getUuid();
309                     responseDocument = getDocstoreHelperService().checkOutDocument(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), marcUUID);
310                     additionalAttributes = responseDocument.getAdditionalAttributes();
311                     editorForm.setCreatedBy(additionalAttributes.getAttribute(AdditionalAttributes.CREATED_BY));
312                     editorForm.setCreatedDate(additionalAttributes.getAttribute(AdditionalAttributes.DATE_ENTERED));
313                     editorForm.setUpdatedBy(additionalAttributes.getAttribute(AdditionalAttributes.UPDATED_BY));
314                     editorForm.setUpdatedDate(additionalAttributes.getAttribute(AdditionalAttributes.LAST_UPDATED));
315                     editorForm.setBibStatus(additionalAttributes.getAttribute(AdditionalAttributes.STATUS));
316                     editorForm.setStatusUpdatedBy(
317                             additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_BY));
318                     editorForm.setStatusUpdatedOn(
319                             additionalAttributes.getAttribute(AdditionalAttributes.STATUS_UPDATED_ON));
320 
321                     if (response.getStatus().equals("Success")) {
322                         editorForm.setDocId(response.getDocuments().get(0).getUuid());
323                         editorForm.setBibId(response.getDocuments().get(0).getUuid());
324                         addDocumentToTree(editorForm);
325                         //                        editorForm.setMessage("Record successfully created.");
326                         editorStatusMessage = "Record successfully created.";
327                         editorStatusMessage = "record.create.message";
328                     }
329                 }
330                 //                workBibMarcForm.setLeader("");
331                 //                workBibMarcForm.setControlFields(Arrays.asList(new MarcEditorControlField()));
332                 //                workBibMarcForm.setDataFields(Arrays.asList(new MarcEditorDataField()));
333                 //                workBibMarcForm.setUuid("");
334 
335             } catch (Exception e) {
336                 StringBuffer marcEditorErrorMessage = new StringBuffer(OLEConstants.MARC_EDITOR_FAILURE)
337                         .append("\n" + e.getMessage());
338                 //workBibMarcForm.setMessage(marcEditorErrorMessage.toString());
339                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "record.save.fail.message");
340             }
341         } else {
342             //            editorForm.setMessage(workBibMarcForm.getMessage());
343             //            editorStatusMessage = workBibMarcForm.getMessage();
344             return workBibMarcForm;
345         }
346         workBibMarcForm.setViewId("WorkBibEditorViewPage");
347         //        return loadDocument(editorForm);
348         WorkBibMarcForm workBibMarcForm1 = (WorkBibMarcForm) loadDocument(editorForm);
349         //workBibMarcForm1.setMessage(editorStatusMessage);
350         GlobalVariables.getMessageMap().getInfoMessages().clear();
351         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorStatusMessage);
352         //System.out.println("GlobalVariables.getMessageMap() " + GlobalVariables.getMessageMap().getInfoMessages().size());
353         editorForm.setShowClose(true);
354         return workBibMarcForm1;
355     }
356 
357     /**
358      * Gets the isNewRecord attribute.
359      * if uuid is null return true else return false.
360      *
361      * @param uuid
362      * @return isNewRecord.
363      */
364     private boolean isNewRecord(String uuid) {
365         return null == uuid;
366     }
367 
368     /**
369      * This method will processResponse,provided the docStore should return response and should have a tokenId
370      *
371      * @param responseFromDocstore
372      * @param editorForm
373      */
374     public void processResponse(String responseFromDocstore, EditorForm editorForm, String uuid) {
375         ResponseHandler responseHandler = new ResponseHandler();
376         Response docStoreResponse = responseHandler.toObject(responseFromDocstore);
377         if (isSuccessfull(docStoreResponse)) {
378             if (responseToOLESentRequired()) {
379                 if (uuid == null || StringUtils.isEmpty(uuid)) {
380                     processNewRecordResponseForOLE(responseFromDocstore);
381                 } else {
382                     processEditRecordResponseForOLE(responseFromDocstore);
383                 }
384             }
385             //editorForm.setMessage(OLEConstants.MARC_EDITOR_SUCCESS);
386             GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "marc.editor.success.message");
387         } else
388             editorForm.setMessage(docStoreResponse.getMessage());
389     }
390 
391     /**
392      * The method will process the new record if it receives response form docStore and should have tokenId.
393      *
394      * @param responseFromDocstore
395      */
396     private void processNewRecordResponseForOLE(String responseFromDocstore) {
397         String instanceUUID = null;
398         List bibInfo = null;
399         DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
400         Response responseRecordForDocstore = getResponseRecordForDocstore(responseFromDocstore);
401 
402         OleEditorResponse oleEditorResponse = new OleEditorResponse();
403         OleBibRecord oleBibRecord = new OleBibRecord();
404 
405         instanceUUID = getUUID(responseRecordForDocstore, OLEConstants.INSTANCE_DOC_TYPE);
406         bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
407         if (bibInfo.isEmpty()) {
408             try {
409                 Thread.sleep(3000);
410             } catch (Exception ex) {
411             }
412             bibInfo = discoveryHelperService.getBibInformationFromInsatnceId(instanceUUID);
413         }
414         oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
415         oleBibRecord.setLinkedInstanceId(instanceUUID);
416         oleBibRecord.setBibUUID(getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE));
417 
418         oleEditorResponse.setOleBibRecord(oleBibRecord);
419         oleEditorResponse.setTokenId(tokenId);
420 
421         OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
422         String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
423 
424 
425         OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl)SpringContext.getBean("oleExposedWebService");
426 
427         oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
428     }
429 
430     /**
431      * The method will process the edit record if it receives response form docStore and should have tokenId.
432      *
433      * @param responseFromDocstore
434      */
435     private void processEditRecordResponseForOLE(String responseFromDocstore) {
436         String bibUUID = null;
437         List bibInfo = null;
438         DiscoveryHelperService discoveryHelperService = GlobalResourceLoader.getService(OLEConstants.DISCOVERY_HELPER_SERVICE);
439         Response responseRecordForDocstore = getResponseRecordForDocstore(responseFromDocstore);
440 
441         OleEditorResponse oleEditorResponse = new OleEditorResponse();
442         OleBibRecord oleBibRecord = new OleBibRecord();
443 
444         bibUUID = getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE);
445         bibInfo = discoveryHelperService.getBibInformationFromBibId(bibUUID);
446         oleBibRecord.setBibAssociatedFieldsValueMap((Map<String, ?>) bibInfo.get(0));
447         HashMap instanceIdentifierHashMap = (HashMap) bibInfo.get(0);
448         ArrayList instanceIdentifierList = (ArrayList) instanceIdentifierHashMap.get(OLEConstants.BIB_INSTANCE_ID);
449         String instanceId = (String) instanceIdentifierList.get(0);
450         oleBibRecord.setLinkedInstanceId(instanceId);
451         oleBibRecord.setBibUUID(getUUID(responseRecordForDocstore, OLEConstants.BIB_DOC_TYPE));
452 
453         oleEditorResponse.setOleBibRecord(oleBibRecord);
454         oleEditorResponse.setTokenId(tokenId);
455 
456         OleEditorResponseHandler oleEditorResponseHandler = new OleEditorResponseHandler();
457         String editorResponseXMLForOLE = oleEditorResponseHandler.toXML(oleEditorResponse);
458 
459         OleExposedWebServiceImpl oleExposedWebService = (OleExposedWebServiceImpl)SpringContext.getBean("oleExposedWebService");
460 
461         oleExposedWebService.addDoctoreResponse(editorResponseXMLForOLE);
462     }
463 
464 
465     /**
466      * Gets the isSuccessfull attribute
467      *
468      * @param docStoreResponse
469      * @return Returns isSuccessfull
470      */
471     private boolean isSuccessfull(Response docStoreResponse) {
472         return docStoreResponse.getStatus().equalsIgnoreCase(OLEConstants.OLE_DOCSTORE_RESPONSE_STATUS);
473     }
474 
475 
476     /**
477      * This method returns True if tokenId is not null,else return False.
478      *
479      * @return boolean
480      */
481     public boolean responseToOLESentRequired() {
482         return null != tokenId;
483     }
484 
485     /**
486      * This method invokes another method to get uuid based on response and docType.
487      *
488      * @param response
489      * @param docType
490      * @return uuid
491      */
492     private String getUUID(Response response, String docType) {
493         List<ResponseDocument> documents = response.getDocuments();
494         return getUUID(documents, docType);
495     }
496 
497     /**
498      * This method gets the uuid based on the List of responseDocument and docType
499      *
500      * @param documents
501      * @param docType
502      * @return uuid
503      */
504     private String getUUID(List<ResponseDocument> documents, String docType) {
505         for (Iterator<ResponseDocument> iterator = documents.iterator(); iterator.hasNext(); ) {
506             ResponseDocument responseDocument = iterator.next();
507             if (responseDocument.getType().equals(docType)) {
508                 return responseDocument.getUuid();
509             } else {
510                 return getUUID(responseDocument.getLinkedDocuments(), docType);
511             }
512         }
513         return null;
514     }
515 
516 
517     /**
518      * Gets the webservice URL using PropertyUtil.
519      *
520      * @return String
521      */
522     public String getURL() {
523         String url = ConfigContext.getCurrentContextConfig().getProperty("oleExposedWebService.url");
524         return url;
525     }
526 
527     /**
528      * This method returns a response record based on the responseFromDocstore.
529      *
530      * @param responseFromDocstore
531      * @return Response
532      */
533     private Response getResponseRecordForDocstore(String responseFromDocstore) {
534         return new ResponseHandler().toObject(responseFromDocstore);
535     }
536 
537 
538     private void updateTreeData(EditorForm editorForm) {
539         int indexOfDocument = 0;
540         List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
541         int i = 0;
542         for (WorkBibDocument bibDocument : workBibDocumentList) {
543             if (editorForm.getDocId().equals(bibDocument.getId())) {
544                 indexOfDocument = i;
545                 break;
546             }
547             i++;
548         }
549         DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
550         WorkBibDocument workBibDocument = new WorkBibDocument();
551         workBibDocument.setId(editorForm.getDocId());
552         workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument);
553 
554         workBibDocumentList.set(indexOfDocument, workBibDocument);
555         editorForm.setWorkBibDocumentList(workBibDocumentList);
556     }
557 
558     /**
559      * This method will Validate the MarcEditorForm and return either True or False
560      * Validation happen based on existence of leader,Tags and values for controlFields and dataFields .
561      *
562      * @param workBibMarcForm
563      * @return valid
564      */
565     public boolean validateMarcEditorData(WorkBibMarcForm workBibMarcForm) {
566         boolean valid;
567         ControlFields controlFields = workBibMarcForm.getMarcControlFields();
568         String leader = workBibMarcForm.getLeader();
569         List<MarcEditorControlField> controlFieldList = workBibMarcForm.getControlFields();
570         List<MarcEditorDataField> dataFieldList = workBibMarcForm.getDataFields();
571         boolean leaderFlag = !leader.trim().equals("");
572         boolean controlFieldFlag = !controlFields.getControlField008().getRawText().equals("");
573         boolean dataFieldFlag = !dataFieldList.get(0).getTag().equals("") && !dataFieldList.get(0).getValue().equals("");
574 
575         valid = leaderFlag && controlFieldFlag && dataFieldFlag ;
576         if (!valid) {
577             //workBibMarcForm.setMessage(OLEConstants.MARC_EDITOR_REQUIRED_MSG);
578             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "marc.editor.required.message");
579             /*workBibMarcForm
580                     .setMessage("<font size='3' color='red'>" + OLEConstants.MARC_EDITOR_REQUIRED_MSG + "</font>");*/
581         } else {
582             valid = validateTitleTag(dataFieldList, workBibMarcForm);
583             boolean  validateTagLength =validateTagLength(dataFieldList, workBibMarcForm) ;
584             boolean  validateInd =validateInd(dataFieldList, workBibMarcForm) ;
585             boolean  validateTagValue=validateData(dataFieldList, workBibMarcForm) ;
586             valid=valid && validateTagLength && validateInd && validateTagValue;
587         }
588 
589         return valid;
590     }
591 
592     private boolean validateInd(List<MarcEditorDataField> dataFieldList, WorkBibMarcForm workBibMarcForm) {
593         for(MarcEditorDataField dataField:dataFieldList) {
594             if(StringUtils.isNotBlank(dataField.getInd1()) && StringUtils.isNotEmpty(dataField.getInd1())  && !dataField.getInd1().equals("#")){
595                 try {
596                     Integer.parseInt(dataField.getInd1());
597                 } catch(NumberFormatException ex) {
598                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "marc.editor.invalid.lengthInd");
599                     return  false;
600                 }
601             }
602             if( !dataField.getInd2().equals("#") && StringUtils.isNotBlank(dataField.getInd2()) && StringUtils.isNotEmpty(dataField.getInd2())){
603                 try {
604                     Integer.parseInt(dataField.getInd2());
605                 } catch(NumberFormatException ex) {
606                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "marc.editor.invalid.lengthInd");
607                     return  false;
608                 }
609             }
610         }
611         return true;
612     }
613 
614     private boolean validateTagLength(List<MarcEditorDataField> dataFieldList, WorkBibMarcForm workBibMarcForm) {
615 
616         for(MarcEditorDataField dataField:dataFieldList) {
617             if(dataField.getTag().length()<3 ){
618                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "marc.editor.invalid.length");
619                 return false;
620             }
621             try {
622                 Integer.parseInt(dataField.getTag());
623             } catch(NumberFormatException ex) {
624                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "marc.editor.invalid.length");
625                 return  false;
626             }
627         }
628         return  true;
629     }
630 
631     private void buildDataFieldList(WorkBibMarcForm workBibMarcForm) {
632         List<MarcEditorDataField> dataFieldList = workBibMarcForm.getDataFields();
633         for(MarcEditorDataField dataField:dataFieldList) {
634 
635             if(dataField.getInd1().equals("") || dataField.getInd1().equals("#") || dataField.getInd1()==null){
636                 dataField.setInd1(" ");
637             }
638 
639             if(dataField.getInd2().equals("")  || dataField.getInd2().equals("#") || dataField.getInd2()==null){
640                 dataField.setInd2(" ");
641             }
642         }
643         workBibMarcForm.setDataFields(dataFieldList);
644     }
645 
646 
647     private void buildLeader(WorkBibMarcForm workBibMarcForm) {
648         workBibMarcForm.setLeader(workBibMarcForm.getLeader().replace("#"," "));
649     }
650 
651     @Override
652     public EditorForm deleteDocument(EditorForm editorForm) {
653         return new WorkBibMarcForm();
654     }
655 
656     @Override
657     public EditorForm createNewRecord(EditorForm editorForm, Request request) {
658         editorForm.setHeaderText("Import Bib Step-4 Bibliographic Editor - MARC Format");
659         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
660         for (RequestDocument reqDoc : request.getRequestDocuments()) {
661             if (reqDoc.getContent() != null && reqDoc.getContent().getContent() != null) {
662                 Collection bibliographicRecords = new BibliographicRecordHandler()
663                         .fromXML(reqDoc.getContent().getContent());
664                 List<BibliographicRecord> bibliographicRecordList = bibliographicRecords.getRecords();
665                 for (BibliographicRecord bibliographicRecord : bibliographicRecordList) {
666                     workBibMarcForm.setLeader(bibliographicRecord.getLeader());
667                     workBibMarcForm.setControlFields(getMarcFormDataHandler().buildMarcEditorControlFields(workBibMarcForm,
668                             bibliographicRecord.getControlfields()));
669                     editorForm.setTitle(getMarcFormDataHandler().buildMarcEditorTitleField(bibliographicRecord.getDatafields()));
670                     workBibMarcForm.setDataFields(
671                             getMarcFormDataHandler().buildMarcEditorDataFields(bibliographicRecord.getDatafields()));
672                     OleBibliographicRecordStatus bibliographicRecordStatus = null;
673                     BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
674                     AdditionalAttributes additionalAttributes = reqDoc.getAdditionalAttributes();
675                     String bibStatusName = additionalAttributes.getAttribute(AdditionalAttributes.STATUS);
676 
677                     editorForm.setBibStatus(bibStatusName);
678                     Map parentCriteria = new HashMap();
679                     parentCriteria.put("bibliographicRecordStatusName", bibStatusName);
680                     bibliographicRecordStatus = boService
681                             .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
682                     if (bibliographicRecordStatus != null) {
683                         editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
684                     }
685                     editorForm.setMessage("Please edit details for the Bib record.");
686                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_ERRORS,"info.edit.details.bib.record");
687                 }
688             }
689         }
690         // Add a node for this document to the left pane tree.
691         addDocumentToTree(editorForm);
692         editorForm.setNeedToCreateInstance(true);
693 
694         workBibMarcForm.setViewId("WorkBibEditorViewPage");
695        setControlFields(workBibMarcForm);
696         return workBibMarcForm;
697     }
698 
699 
700     public void setControlFields(WorkBibMarcForm workBibMarcForm) {
701         List<ControlField006Text> controlField006Texts = workBibMarcForm.getMarcControlFields().getControlFields006List();
702         List<ControlField006Text> controlField006EditText = new ArrayList<>();
703         for (ControlField006Text controlField006Text : controlField006Texts) {
704             if (controlField006Text.getRawText() != null) {
705                 controlField006Text.setRawText(controlField006Text.getRawText().replaceAll(" ", "#"));
706                 controlField006EditText.add(controlField006Text);
707             }
708         }
709         if(controlField006EditText.size()>0){
710         workBibMarcForm.getMarcControlFields().setControlFields006List(controlField006EditText);
711         }
712         List<ControlField007Text> controlField007Texts = workBibMarcForm.getMarcControlFields().getControlFields007List
713                 ();
714         List<ControlField007Text> controlField007EditText = new ArrayList<>();
715         for (ControlField007Text controlField007Text : controlField007Texts) {
716             if (controlField007Text.getRawText() != null) {
717                 controlField007Text.setRawText(controlField007Text.getRawText().replaceAll(" ", "#"));
718                 controlField007EditText.add(controlField007Text);
719             }
720         }
721         if(controlField007EditText.size()>0){
722         workBibMarcForm.getMarcControlFields().setControlFields007List(controlField007EditText);
723         }
724         ControlField008 controlField008 = workBibMarcForm.getMarcControlFields().getControlField008();
725         if (controlField008 != null) {
726             controlField008.setRawText(controlField008.getRawText().replaceAll(" ", "#"));
727             workBibMarcForm.getMarcControlFields().setControlField008(controlField008);
728         }
729        if( workBibMarcForm.getLeader()!=null){
730         workBibMarcForm.setLeader(workBibMarcForm.getLeader().replaceAll(" ", "#"));
731        }
732     }
733 
734     @Override
735     public EditorForm editNewRecord(EditorForm editorForm, Request req) {
736         WorkBibMarcForm workBibMarcForm = (WorkBibMarcForm) editorForm.getDocumentForm();
737         if (!validateMarcEditorData(workBibMarcForm)) {
738             workBibMarcForm.setValidInput(false);
739             return workBibMarcForm;
740         }
741         String bibliographicRecordStatusCode = editorForm.getOleBibliographicRecordStatus()
742                 .getBibliographicRecordStatusCode();
743         String content = getMarcFormDataHandler().buildBibRecordForDocStore(workBibMarcForm);
744 //        req.getRequestDocuments().get(0).getContent().setContent(content);
745         RequestDocument reqDoc = req.getRequestDocuments().get(0);
746         reqDoc.getContent().setContent(content);
747         AdditionalAttributes additionalAttributes = reqDoc.getAdditionalAttributes();
748         editorForm.setCreatedBy(additionalAttributes.getAttribute(AdditionalAttributes.CREATED_BY));
749         editorForm.setCreatedDate(additionalAttributes.getAttribute(AdditionalAttributes.DATE_ENTERED));
750         OleBibliographicRecordStatus bibliographicRecordStatus = null;
751         BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
752         if (bibliographicRecordStatusCode != null) {
753             Map parentCriteria = new HashMap();
754             parentCriteria.put("bibliographicRecordStatusCode", bibliographicRecordStatusCode);
755             bibliographicRecordStatus = boService
756                     .findByPrimaryKey(OleBibliographicRecordStatus.class, parentCriteria);
757         }
758 
759         if (bibliographicRecordStatus != null) {
760             additionalAttributes.setAttribute(AdditionalAttributes.STATUS, bibliographicRecordStatus.getBibliographicRecordStatusName());
761             editorForm.setOleBibliographicRecordStatus(bibliographicRecordStatus);
762 
763         } else {
764             additionalAttributes.setAttribute(AdditionalAttributes.STATUS, "");
765         }
766         additionalAttributes.setAttribute(AdditionalAttributes.STAFFONLYFLAG,String.valueOf(editorForm.isStaffOnlyFlagForBib()));
767 
768         return editorForm;
769     }
770 
771     @Override
772     public String saveDocument(Request request, EditorForm editorForm) {
773         return null;  //To change body of implemented methods use File | Settings | File Templates.
774     }
775 
776     private void addDocumentToTree(EditorForm editorForm) {
777         // TODO: Make sure the same document is not added more than once.
778         List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
779         int indexOfDocument = 0;
780         int i = 0;
781         String title = "New Bib1";
782         boolean updateTitle = false;
783         if (null == workBibDocumentList) {
784             workBibDocumentList = new ArrayList<WorkBibDocument>();
785         }
786         workBibDocumentList = new ArrayList<WorkBibDocument>();
787         WorkBibDocument tempDocument = new WorkBibDocument();
788         if (null == editorForm.getDocId()) {
789             LOG.info("workBibDocumentList size before remove-->" + workBibDocumentList.size());
790             for (WorkBibDocument workBibDocument : workBibDocumentList) {
791                 if (workBibDocument.getTitle().equalsIgnoreCase("New Bib1")) {
792                     tempDocument = workBibDocument;
793                     // workBibDocumentList.remove(workBibDocument);
794                 }
795             }
796             workBibDocumentList.remove(tempDocument);
797             LOG.info("workBibDocumentList size after remove-->" + workBibDocumentList.size());
798 
799             WorkBibDocument workBibDocument = new WorkBibDocument();
800             workBibDocument.setTitle(title);
801             workBibDocumentList.add(workBibDocument);
802         } else {
803             boolean isUpadated = false;
804             for (WorkBibDocument bibDocument : workBibDocumentList) {
805                 if (bibDocument.getId() != null && bibDocument.getId().equals(editorForm.getDocId())) {
806                     isUpadated = true;
807                     break;
808                 } else if (bibDocument.getTitle().equals(title)) {
809                     indexOfDocument = i;
810                     updateTitle = true;
811                     break;
812                 }
813                 i++;
814             }
815             if (!isUpadated) {
816                 WorkBibDocument workBibDocument = new WorkBibDocument();
817                 workBibDocument.setId(editorForm.getDocId());
818                 DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
819                 workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument);
820                 if (updateTitle) {
821                     workBibDocumentList.set(indexOfDocument, workBibDocument);
822                 } else {
823                     workBibDocumentList.add(workBibDocument);
824                 }
825             }
826 
827         }
828         editorForm.setWorkBibDocumentList(workBibDocumentList);
829     }
830 
831     @Override
832     public EditorForm addORDeleteFields(EditorForm editorForm, HttpServletRequest request) {
833 
834         String methodName = request.getParameter("methodToCall");
835         if (methodName.equalsIgnoreCase("addControlField006")) {
836             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
837             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
838             index++;
839             List<ControlField006Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields006List();
840             marcEditorControlFieldList.add(index, new ControlField006Text());
841             marcEditorForm.getMarcControlFields().setControlFields006List(marcEditorControlFieldList);
842             editorForm.setDocumentForm(marcEditorForm);
843         } else if (methodName.equalsIgnoreCase("removeControlField006")) {
844             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
845             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
846             List<ControlField006Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields006List();
847             if (marcEditorControlFieldList.size() > 1) {
848                 marcEditorControlFieldList.remove(index);
849             }
850             editorForm.setDocumentForm(marcEditorForm);
851         } else if (methodName.equalsIgnoreCase("addControlField007")) {
852             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
853             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
854             index++;
855             List<ControlField007Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields007List();
856             marcEditorControlFieldList.add(index, new ControlField007Text());
857             marcEditorForm.getMarcControlFields().setControlFields007List(marcEditorControlFieldList);
858             editorForm.setDocumentForm(marcEditorForm);
859         } else if (methodName.equalsIgnoreCase("removeControlField007")) {
860             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
861             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
862             List<ControlField007Text> marcEditorControlFieldList = marcEditorForm.getMarcControlFields().getControlFields007List();
863             if (marcEditorControlFieldList.size() > 1) {
864                 marcEditorControlFieldList.remove(index);
865             }
866             editorForm.setDocumentForm(marcEditorForm);
867         } else if (methodName.equalsIgnoreCase("addDataField")) {
868             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
869             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
870             index++;
871             List<MarcEditorDataField> editorDataFieldList = marcEditorForm.getDataFields();
872             for(MarcEditorDataField editorDataField : editorDataFieldList) {
873                 String modifiedValue = editorDataField.getValue().replace("\"", "&quot;");
874                 editorDataField.setValue(modifiedValue);
875             }
876             editorDataFieldList.add(index, new MarcEditorDataField());
877             marcEditorForm.setDataFields(editorDataFieldList);
878             editorForm.setDocumentForm(marcEditorForm);
879         } else if (methodName.equalsIgnoreCase("removeDataField")) {
880             WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) editorForm.getDocumentForm();
881             int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
882             List<MarcEditorDataField> marcEditorDataFieldList = marcEditorForm.getDataFields();
883             if (marcEditorDataFieldList.size() > 1) {
884                 marcEditorDataFieldList.remove(index);
885             }
886             for(MarcEditorDataField marcDataField : marcEditorDataFieldList) {
887                 String modifiedValue = marcDataField.getValue().replace("\"", "&quot;");
888                 marcDataField.setValue(modifiedValue);
889             }
890             marcEditorForm.setDataFields(marcEditorDataFieldList);
891             editorForm.setDocumentForm(marcEditorForm);
892         }
893         return editorForm;
894     }
895 
896     /**
897      *  This method will return instance of MarcEditorForm
898      * @param request
899      * @return MarcEditorForm
900      */
901 
902 /*
903     @Override
904     protected WorkBibMarcForm createInitialForm(HttpServletRequest request) {
905         return new WorkBibMarcForm();
906     }
907 */
908 
909     /**
910      * This method takes the initial request when click on MarcEditor Screen.
911      * @param form
912      * @param result
913      * @param request
914      * @param response
915      * @return ModelAndView
916      */
917 /*
918     @Override
919     @RequestMapping(params = "methodToCall=start")
920     public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
921                               HttpServletRequest request, HttpServletResponse response) {
922         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
923         ModelAndView modelAndView = super.start(form,result,request,response);
924         return getUIFModelAndView(marcEditorForm, "WorkBibEditorViewPage");
925     }
926 */
927 
928     /**
929      * This method will add the controlField record based on the selected Line index and updates the component.
930      * @param form
931      * @param result
932      * @param request
933      * @param response
934      * @return ModelAndView
935      */
936 /*
937     @RequestMapping(params = "methodToCall=addControlField")
938     public ModelAndView addControlField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
939                                         HttpServletRequest request, HttpServletResponse response) {
940         //WorkBibForm marcEditorForm = (WorkBibForm) form;
941         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
942         int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
943         index++;
944         List<MarcEditorControlField> marcEditorControlFieldList = marcEditorForm.getControlFields();
945         marcEditorControlFieldList.add(index, new MarcEditorControlField());
946         return super.updateComponent(marcEditorForm, result, request, response);
947     }
948 */
949 
950     /**
951      *  This method will remove the controlField based on the index position and updates the component.
952      * @param form
953      * @param result
954      * @param request
955      * @param response
956      * @return ModelAndView
957      */
958 /*
959     @RequestMapping(params = "methodToCall=removeControlField")
960     public ModelAndView removeControlField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
961                                            HttpServletRequest request, HttpServletResponse response) {
962        // WorkBibForm marcEditorForm = (WorkBibForm) form;
963         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
964         int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
965         List<MarcEditorControlField> editorControlFieldList = marcEditorForm.getControlFields();
966         if (editorControlFieldList.size() > 1)
967             editorControlFieldList.remove(index);
968         return super.updateComponent(marcEditorForm, result, request, response);
969     }
970 */
971 
972     /**
973      *  This method will add the datField record based on the selected Line index and updates the component.
974      * @param form
975      * @param result
976      * @param request
977      * @param response
978      * @return ModelAndView
979      */
980 /*
981     @RequestMapping(params = "methodToCall=addDataField")
982     public ModelAndView addDataField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
983                                      HttpServletRequest request, HttpServletResponse response) {
984        // WorkBibForm marcEditorForm = (WorkBibForm) form;
985         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
986         int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
987         index++;
988         List<MarcEditorDataField> editorDataFieldList = marcEditorForm.getDataFields();
989         editorDataFieldList.add(index, new MarcEditorDataField());
990         return super.updateComponent(marcEditorForm, result, request, response);
991     }
992 */
993 
994     /**
995      *    This method will remove the dataField based on the index position and updates the component.
996      * @param form
997      * @param result
998      * @param request
999      * @param response
1000      * @return ModelAndView
1001      */
1002 /*
1003     @RequestMapping(params = "methodToCall=removeDataField")
1004     public ModelAndView removeDataField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1005                                         HttpServletRequest request, HttpServletResponse response) {
1006        // WorkBibForm marcEditorForm = (WorkBibForm) form;
1007         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
1008         int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1009         List<MarcEditorDataField> marcEditorDataFieldList = marcEditorForm.getDataFields();
1010         if (marcEditorDataFieldList.size() > 1)
1011             marcEditorDataFieldList.remove(index);
1012         return super.updateComponent(marcEditorForm, result, request, response);
1013     }
1014 */
1015 
1016     /**
1017      *   This method load the MarcEditor records based on uuid.
1018      *
1019      * @param form
1020      * @param result
1021      * @param request
1022      * @param response
1023      * @return ModelAndView
1024      */
1025 /*
1026     @RequestMapping(params = "methodToCall=loadMarcRecord")
1027     public ModelAndView load(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1028                              HttpServletRequest request, HttpServletResponse response) {
1029         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
1030         String existingUUID = request.getParameter("uuid");
1031         if (null == existingUUID || StringUtils.isEmpty(existingUUID)) {
1032             existingUUID = marcEditorForm.getUuid();
1033         }
1034         try {
1035             marcEditorForm.setExisting("true");
1036             String docStoreData = getDocstoreHelperService().getDocstoreData(existingUUID);
1037             Collection bibliographicRecords = new BibliographicRecordHandler().fromXML(docStoreData);
1038             List<BibliographicRecord> bibliographicRecordList = bibliographicRecords.getRecords();
1039             BibliographicRecord bibliographicRecord = bibliographicRecordList.get(0);
1040             marcEditorForm.setLeader(bibliographicRecord.getLeader());
1041             marcEditorForm.setControlFields(getMarcFormDataHandler().buildMarcEditorControlFields(bibliographicRecord.getControlfields()));
1042             marcEditorForm.setDataFields(getMarcFormDataHandler().buildMarcEditorDataFields(bibliographicRecord.getDatafields()));
1043         } catch (Exception e) {
1044             e.printStackTrace();
1045         }
1046         return getUIFModelAndView(marcEditorForm, "WorkBibEditorViewPage");
1047     }
1048 */
1049 
1050     /**
1051      * Gets the docstoreHelperService attribute.
1052      *
1053      * @return DocstoreHelperService
1054      */
1055     private DocstoreHelperService getDocstoreHelperService() {
1056         if (null == docstoreHelperService) {
1057             return new DocstoreHelperService();
1058         }
1059         return docstoreHelperService;
1060     }
1061 
1062     /**
1063      * Gets the MarcEditorFormDataHandler attribute.
1064      *
1065      * @return MarcEditorFormDataHandler
1066      */
1067     private MarcEditorFormDataHandler getMarcFormDataHandler() {
1068         if (null == marcEditorFormDataHandler) {
1069             marcEditorFormDataHandler = new MarcEditorFormDataHandler();
1070         }
1071         return marcEditorFormDataHandler;
1072     }
1073 
1074     @RequestMapping(params = "methodToCall=EditNewInstance")
1075     public ModelAndView EditNewInstance(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1076                                         HttpServletRequest request, HttpServletResponse response) {
1077 
1078         WorkBibMarcForm marcEditorForm = (WorkBibMarcForm) form;
1079         Request req = (Request) request.getSession().getAttribute("requestObject");
1080         String content = getMarcFormDataHandler().buildBibRecordForDocStore(marcEditorForm);
1081         req.getRequestDocuments().get(0).getContent().setContent(content);
1082 
1083         EditorController editorController = new EditorController();
1084         request.setAttribute("docCategory", "work");
1085         request.setAttribute("docType", "instnace");
1086         request.setAttribute("docFormat", "oleml");
1087 
1088         ModelAndView modelAndView = editorController.load(form, result, request, response);
1089 
1090 
1091         /*  EditorForm documentForm = (EditorForm) form;
1092 Request req = (Request) request.getSession().getAttribute("requestObject");
1093 // Get documentList from session.
1094 List<WorkBibDocument> workBibDocumentList = (List)request.getSession().getAttribute("treeDocumentList");
1095 if (null != workBibDocumentList) {
1096     ((EditorForm) form).setWorkBibDocumentList(workBibDocumentList);
1097 }
1098 if(documentForm.getViewId().equalsIgnoreCase("WorkHoldingsViewPage")){
1099     // Identify the document editor to be used for the requested document.
1100     DocumentEditor documentEditor = DocumentEditorFactory.getInstance().getDocumentEditor("work", "item", "oleml");
1101 
1102 
1103     documentForm = documentEditor.CreateNewBibRInstance((EditorForm) form,req );
1104     documentForm.setNeedToCreateInstance("false");
1105 
1106 }else{
1107 
1108 
1109     BibliographicRecord bibliographicRecord = new BibliographicRecord();
1110     bibliographicRecord.setLeader(documentForm.getWorkBibMarcForm().getLeader());
1111     bibliographicRecord.setControlfields(getMarcFormDataHandler().buldBibliographicContrlFields(documentForm.getWorkBibMarcForm().getControlFields()));
1112     bibliographicRecord.setDatafields(getMarcFormDataHandler().buildBibliographicDataFields(documentForm.getWorkBibMarcForm().getDataFields()));
1113     String content = new BibliographicRecordHandler().generateXML(bibliographicRecord);
1114 
1115 
1116     req.getRequestDocuments().get(0).getContent().setContent(content);
1117 
1118 
1119 
1120     ((EditorForm) form).setDocCategory("work");
1121     ((EditorForm) form).setDocType("instance");
1122     ((EditorForm) form).setDocFormat("oleml");
1123 
1124 
1125 
1126     // Identify the document editor to be used for the requested document.
1127     DocumentEditor documentEditor = DocumentEditorFactory.getInstance().getDocumentEditor("work", "instance", "oleml");
1128 
1129     documentForm = documentEditor.CreateNewBibRInstance((EditorForm) form,req );
1130 }
1131 
1132 // Set the output (response) form containing document info into the current form.
1133 ((EditorForm) form).setDocumentForm(documentForm);
1134 // Set documentlist to session.
1135 request.getSession().setAttribute("treeDocumentList", ((EditorForm)form).getWorkBibDocumentList());
1136 
1137 // Build or update left pane data (tree structure of documents)
1138 getEditorFormDataHandler().buildLeftPaneData((EditorForm) form);
1139 
1140 // Return the next view to be shown to user.
1141 ModelAndView modelAndView = getUIFModelAndView(form, documentForm.getViewId());    */
1142         return modelAndView;
1143 
1144     }
1145 
1146     /**
1147      * This method validate the title Tag in the MarcEditorForm and retur either True or False.
1148      * in the marcEditorForm one of the Tags must be 245 and the values should starts with    "|a" .
1149      *
1150      * @param dataFieldList
1151      * @param workBibMarcForm
1152      * @return isValid
1153      */
1154     private boolean validateTitleTag(List<MarcEditorDataField> dataFieldList, WorkBibMarcForm workBibMarcForm) {
1155         boolean isValidTitleTag = false;
1156         boolean isValidTitleValue = false;
1157         boolean isValid = false;
1158 
1159         for (Iterator<MarcEditorDataField> iterator = dataFieldList.iterator(); iterator.hasNext(); ) {
1160             MarcEditorDataField marcEditorDataField = iterator.next();
1161             isValidTitleTag = marcEditorDataField.getTag().equals(OLEConstants.MARC_EDITOR_TITLE_245);
1162 //            isValidTitleValue = marcEditorDataField.getValue().startsWith(OLEConstants.MARC_EDITOR_TITLE_LETTER);
1163             String title = marcEditorDataField.getValue();
1164             isValidTitleValue = isValidTitle(title);
1165             if (isValidTitleTag) {
1166                 isValid = !isValidTitleValue ? false : true;
1167             }
1168         }
1169         if (!isValid)
1170             //workBibMarcForm.setMessage(OLEConstants.MARC_EDITOR_INVALID_TITLE);
1171             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"marc.editor.invalid.title");
1172 
1173         return isValid;
1174     }
1175 
1176     private boolean validateData(List<MarcEditorDataField> dataFieldList, WorkBibMarcForm workBibMarcForm) {
1177         boolean isValid=true;
1178         for (MarcEditorDataField dataField : dataFieldList) {
1179             isValid=isValidFieldValue(dataField.getValue(),dataField.getTag());
1180             if(!isValid){
1181                 break;
1182             }
1183 
1184         }
1185         return isValid;
1186     }
1187 
1188     private boolean isValidFieldValue(String data, String tag) {
1189         if (data != null && StringUtils.isNotEmpty(data)) {
1190             ArrayList<Integer> positions = new ArrayList<>();
1191             for (int i = 0; i < data.length(); i++) {
1192                 if (data.charAt(i) == '|') {
1193                     positions.add(i);
1194                 }
1195 
1196             }
1197             Boolean isValidAlphabet = true;
1198             Boolean isValidNumeric = true;
1199             String numeric = "0123456789";
1200 
1201             if (tag.startsWith("9")) {
1202                 if (!data.startsWith("|a")) {
1203                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "marc.editor.invalid.Nine", tag);
1204                     return false;
1205                 }
1206 
1207             } else {
1208                 if (!data.startsWith("|")) {
1209                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.missing.pipe.at", tag);
1210                     return false;
1211                 }
1212 
1213                 if (!data.contains("|")) {
1214                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.missing.pipe.at", tag);
1215                     return false;
1216                 }
1217 
1218                 if (tag.equals("000") || tag.equals("001") || tag.equals("002") || tag.equals("003") || tag.equals("004") || tag.equals("005") || tag.equals("006") || tag.equals("007") || tag.equals("008") || tag.equals("009")) {
1219                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.valid.data.value", tag);
1220                     return false;
1221                 }
1222 
1223                 //Added for accepting 1XX to 8XX code
1224                 else {
1225                     for (Integer position : positions) {
1226 
1227                         if (!data.substring(position, (position + 1)).equals("|")) {
1228                             isValidAlphabet = false;
1229                         }
1230 
1231                         if (data.length() > (position + 1) && !data.substring((position + 1), (position + 2)).matches("[a-z]")) {
1232                             isValidAlphabet = false;
1233                         }
1234 
1235                         if (data.length() > (position + 1) && !data.substring((position + 1), (position + 2)).matches("[a-z]")) {
1236                             if (data.length() > (position + 1) && numeric.indexOf(data.substring((position + 1), (position + 2))) < 0) {
1237                                 isValidNumeric = false;
1238                             }
1239                         }
1240 
1241                         if (data.length() <= (position + 2)) {
1242                             //GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.valid.text");
1243                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.valid.text.at", tag);
1244                             return false;
1245                         }
1246                         if (!isValidAlphabet && !isValidNumeric) {
1247                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.enter.valid.text.at", tag);
1248                             return false;
1249                         }
1250                     }
1251                 }
1252             }
1253         } else {
1254             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.bib.empty.text.at", tag);
1255             return false;
1256         }
1257         return true;
1258     }
1259 
1260 
1261     private void buildDocsFromResponse() {
1262         String deleteVerifyResponse = "<response>\n" +
1263                 "\t<documents>\n" +
1264                 "\t\t<document id=\"1\" category=\"work\" type=\"bib\" format=\"marc\">\n" +
1265                 "\t\t\t<uuid>Bib1</uuid>\n" +
1266                 "\t\t</document>\n" +
1267                 "\t\t<document id=\"2\" category=\"work\" type=\"instance\" format=\"oleml\">\n" +
1268                 "\t\t\t<uuid> Inst1</uuid>\n" +
1269                 "\t\t</document>\n" +
1270                 "\t</documents>\n" +
1271                 "\t<user>khuntley</user>\n" +
1272                 "\t<operation>delete</operation>\n" +
1273                 "\t<status>Success</status>\n" +
1274                 "\t<message>Record deleted successfullyy</message>\n" +
1275                 "  </response>";
1276 
1277         Response response = new ResponseHandler().toObject(deleteVerifyResponse);
1278 
1279 
1280     }
1281 
1282     @Override
1283     public EditorForm deleteVerify(EditorForm editorForm) throws Exception {
1284         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
1285         /* DocStoreUtility docStoreUtility;
1286         docStoreUtility = DocStoreUtilityImpl.getInstance();*/
1287 
1288         String docId = editorForm.getDocId();
1289         editorForm.setShowDeleteTree(true);
1290         //  docStoreUtility.connectToDocStore("deleteVerify",docId);
1291         //  String operation = "deleteVerify";
1292         //String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1293 
1294         List<String> uuidList = new ArrayList<>(0);
1295         uuidList.add(editorForm.getDocId());
1296         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1297         Node<DocumentTreeNode, String> docTree = documentSelectionTree.add(uuidList, DocType.BIB.getDescription());
1298         editorForm.getDocTree().setRootElement(docTree);
1299 
1300         workBibMarcForm.setViewId("DeleteViewPage");
1301 
1302         return workBibMarcForm;
1303     }
1304 
1305 
1306     private Node<DocumentTreeNode, String> buildDocSelectionTree(String responseXml) throws SolrServerException {
1307         Response response = new ResponseHandler().toObject(responseXml);
1308         List<ResponseDocument> responseDocumentList = response.getDocuments();
1309         List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
1310         List<WorkBibDocument> bibDocumentList = new ArrayList<WorkBibDocument>();
1311         List<WorkInstanceDocument> instanceDocumentList = new ArrayList<WorkInstanceDocument>();
1312         WorkHoldingsDocument workHoldingsDocument = null;
1313         WorkInstanceDocument workInstanceDocument = null;
1314         WorkBibDocument workBibDocument = null;
1315         WorkItemDocument workItemDocument = null;
1316         List<String> uuidList = new ArrayList<String>();
1317         String docType = null;
1318 
1319         for (ResponseDocument responseDocument : responseDocumentList) {
1320 
1321             if (responseDocument.getType().equalsIgnoreCase(DocType.ITEM.getCode())) {
1322                 workItemDocument = new WorkItemDocument();
1323                 workItemDocument.setItemIdentifier(responseDocument.getUuid());
1324                 uuidList.add(responseDocument.getUuid());
1325 
1326                 docType = responseDocument.getType();
1327                 workItemDocumentList.add(workItemDocument);
1328 
1329             } else if (responseDocument.getType().equalsIgnoreCase(DocType.HOLDINGS.getCode())) {
1330                 workHoldingsDocument = new WorkHoldingsDocument();
1331                 docType = responseDocument.getType();
1332                 workHoldingsDocument.setHoldingsIdentifier(responseDocument.getUuid());
1333                 uuidList.add(responseDocument.getUuid());
1334             } else if (responseDocument.getType().equalsIgnoreCase(DocType.BIB.getDescription())) {
1335                 workBibDocument = new WorkBibDocument();
1336                 uuidList.add(responseDocument.getUuid());
1337                 workBibDocument.setId(responseDocument.getUuid());
1338                 docType = responseDocument.getType();
1339                 bibDocumentList.add(workBibDocument);
1340 
1341 
1342             } else if (responseDocument.getType().equalsIgnoreCase(DocType.INSTANCE.getCode())) {
1343                 workInstanceDocument = new WorkInstanceDocument();
1344                 workInstanceDocument.setInstanceIdentifier(responseDocument.getUuid());
1345                 uuidList.add(responseDocument.getUuid());
1346                 docType = responseDocument.getType();
1347                 instanceDocumentList.add(workInstanceDocument);
1348             }
1349         }
1350         if (workItemDocumentList.size() > 0) {
1351             if (workInstanceDocument != null) {
1352                 workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
1353                 workInstanceDocument.setItemDocumentList(workItemDocumentList);
1354             }
1355         }
1356         if (instanceDocumentList.size() > 0) {
1357             if (workBibDocument != null) {
1358                 workBibDocument.setWorkInstanceDocumentList(instanceDocumentList);
1359             }
1360         }
1361 
1362         DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1363 
1364         Node<DocumentTreeNode, String> rootNode = documentSelectionTree.add(uuidList, docType);
1365 
1366         return rootNode;
1367     }
1368 
1369 
1370     @Override
1371     public EditorForm delete(EditorForm editorForm) throws Exception {
1372         WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
1373         BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
1374         boolean itemCheck = false;
1375         String docId = editorForm.getDocId();
1376         String operation = "delete";
1377         List<String> bibIdList = new ArrayList<String>();
1378         Map<String, String> map = new HashMap<>();
1379         map.put(OLEConstants.BIB_ID, docId);
1380         List<OleCopy> listOfValues = (List<OleCopy>) boService.findMatching(OleCopy.class, map);
1381         if (listOfValues.size() != 0) {
1382             itemCheck = true;
1383             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_PURCHASE_ORDER_FAIL_MESSAGE, "Item");
1384             editorForm.setShowDeleteTree(false);
1385         }
1386         else{
1387             List<String> itemList = getDocstoreHelperService().getItemIdList(docId);
1388              for(String itemUuid : itemList) {
1389                  Map<String, String> uuidMap = new HashMap<>();
1390                  uuidMap.put("itemUuid", itemUuid);
1391                  List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) boService.findMatching(OleLoanDocument.class, uuidMap);
1392                  if (oleLoanDocuments.size() != 0) {
1393                      itemCheck = true;
1394                      GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_LOANED_FAIL_MESSAGE);
1395                      editorForm.setShowDeleteTree(false);
1396                      break;
1397                  } else {
1398                      List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) boService.findMatching(OleDeliverRequestBo.class, uuidMap);
1399                      if (oleDeliverRequestBos.size() != 0) {
1400                          itemCheck = true;
1401                          GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_REQUEST_FAIL_MESSAGE);
1402                          editorForm.setShowDeleteTree(false);
1403                          break;
1404                      }
1405                  }
1406              }
1407         }
1408         if (!itemCheck) {
1409             String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1410             List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
1411             WorkBibDocument docToRemove = null;
1412             for (WorkBibDocument workBibDocument : workBibDocumentList) {
1413                 if (workBibDocument.getId().equals(editorForm.getDocId())) {
1414                     docToRemove = workBibDocument;
1415                 }
1416             }
1417             if (docToRemove != null) {
1418                 workBibDocumentList.remove(docToRemove);
1419             }
1420             editorForm.setWorkBibDocumentList(workBibDocumentList);
1421             Response response = new ResponseHandler().toObject(responseXml);
1422             for(ResponseDocument responseDocument :response.getDocuments()){
1423                 if(responseDocument.getStatus().contains("failure")){
1424                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response" ,responseDocument.getStatusMessage());
1425                 }else if(responseDocument.getStatus().contains("success")){
1426                     GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.delete.message");
1427                     editorForm.setShowDeleteTree(false);
1428                 }else{
1429                     GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.delete.fail.message");
1430                 }
1431             }
1432             /*if (responseXml.contains("Success") && !responseXml.contains("failure")) {
1433                 editorForm.setMessage("Records deleted successfully.");
1434                 editorForm.setShowDeleteTree(false);
1435             } else {
1436                 editorForm.setMessage("Failed to delete records.");
1437             }*/
1438             workBibMarcForm.setViewId("DeleteViewPage");
1439 
1440         }
1441         return workBibMarcForm;
1442     }
1443 
1444     @Override
1445     public EditorForm addORRemoveExtentOfOwnership(EditorForm editorForm, HttpServletRequest request) {
1446         return null;  //To change body of implemented methods use File | Settings | File Templates.
1447     }
1448 
1449     @Override
1450     public EditorForm addORRemoveAccessInformationAndHoldingsNotes(EditorForm editorForm, HttpServletRequest request) {
1451         return null;  //To change body of implemented methods use File | Settings | File Templates.
1452     }
1453 
1454     @Override
1455     public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1456         return null;  //To change body of implemented methods use File | Settings | File Templates.
1457     }
1458 
1459     /**
1460      * This method verifies the title field (245 |a) has a value and returns true if exists.
1461      *
1462      * @param title
1463      * @return
1464      */
1465     private boolean isValidTitle(String title) {
1466         if (title.contains("|a")) {
1467             String[] titles = title.split("[|]");
1468 
1469             for (String titleValue : titles) {
1470                 if (titleValue.startsWith("a") && titleValue.length() > 1) {
1471                     return true;
1472                 }
1473             }
1474         }
1475         return false;
1476     }
1477 
1478     /**
1479      * Set tag and value for Control field
1480      *
1481      * @param tag
1482      * @param value
1483      * @return
1484      */
1485     private MarcEditorControlField getMarcEditorControlField(String tag, String value) {
1486         MarcEditorControlField marcEditorControlField = new MarcEditorControlField();
1487         marcEditorControlField.setTag(tag);
1488         marcEditorControlField.setValue(value);
1489         return marcEditorControlField;
1490     }
1491 
1492     /**
1493      * Build controlField list with tag and value pairs.
1494      *
1495      * @param workBibMarcForm
1496      */
1497     private void buildControlFieldList(WorkBibMarcForm workBibMarcForm) {
1498         ControlFields controlFields = workBibMarcForm.getMarcControlFields();
1499 
1500         Date dt = new Date();
1501         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss.S");
1502         controlFields.setControlField005(sdf.format(dt).substring(0, 16));
1503 
1504         List<MarcEditorControlField> marcEditorControlFields = new ArrayList<MarcEditorControlField>();
1505         if (StringUtils.isNotEmpty(controlFields.getControlField001())) {
1506             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_001,
1507                     controlFields.getControlField001()));
1508         }
1509         if (StringUtils.isNotEmpty(controlFields.getControlField003())) {
1510             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_003,
1511                     controlFields.getControlField003()));
1512         }
1513         if (StringUtils.isNotEmpty(controlFields.getControlField005())) {
1514             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_005,
1515                     controlFields.getControlField005()));
1516         }
1517         if (controlFields.getControlFields006List().size() > 0) {
1518             for (ControlField006Text controlField006Text : controlFields.getControlFields006List()) {
1519                 if (controlField006Text.getRawText() != null && StringUtils.isNotEmpty(controlField006Text.getRawText()))
1520                     marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_006,
1521                             controlField006Text.getRawText().replace("#"," ")));
1522             }
1523         }
1524         if (controlFields.getControlFields007List().size() > 0) {
1525             for (ControlField007Text controlField007Text : controlFields.getControlFields007List()) {
1526                 if (controlField007Text.getRawText() != null && StringUtils.isNotEmpty(controlField007Text.getRawText()))
1527                     marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_007,
1528                             controlField007Text.getRawText().replace("#", " ")));
1529             }
1530         }
1531         if (StringUtils.isNotEmpty(controlFields.getControlField008().getRawText())) {
1532             sdf = new SimpleDateFormat("yyMMdd");
1533        if(controlFields.getControlField008().getRawText().substring(0,6).contains("#")){
1534            controlFields.getControlField008().setRawText(sdf.format(dt)+controlFields.getControlField008().getRawText
1535                    ().substring(6,40));
1536        }
1537 
1538             marcEditorControlFields.add(getMarcEditorControlField(ControlFields.CONTROL_FIELD_008,
1539                     controlFields.getControlField008().getRawText().replace("#"," ")));
1540         }
1541         workBibMarcForm.setControlFields(marcEditorControlFields);
1542     }
1543 
1544     @Override
1545     public EditorForm showBibs(EditorForm editorForm) {
1546         return null;
1547     }
1548 
1549     public EditorForm copy(EditorForm editorForm){
1550         return null;
1551     }
1552 
1553 
1554     @Override
1555     public Boolean isValidUpdate(EditorForm editorForm) {
1556         String docId = editorForm.getDocId();
1557         Boolean isValidUpdate = true;
1558         if (null != docId) {
1559             try {
1560                 ResponseDocument responseDocument = getDocstoreHelperService().checkOutDocument(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), docId);
1561                 AdditionalAttributes additionalAttributes = responseDocument.getAdditionalAttributes();
1562                 if (!additionalAttributes.getAttribute(AdditionalAttributes.LAST_UPDATED).equals(editorForm
1563                         .getUpdatedDate())) {
1564                     isValidUpdate = false;
1565                 }
1566             } catch (Exception e) {
1567                 LOG.error("New Record...."+docId);
1568             }
1569         }
1570         return isValidUpdate;
1571     }
1572 
1573 }