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