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