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