001package org.kuali.ole.describe.controller;
002
003import org.apache.commons.lang.StringUtils;
004import org.apache.log4j.Logger;
005import org.apache.solr.client.solrj.SolrServerException;
006import org.kuali.ole.OLEConstants;
007import org.kuali.ole.OLEParameterConstants;
008import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
009import org.kuali.ole.deliver.bo.OleLoanDocument;
010import org.kuali.ole.describe.bo.DocumentSelectionTree;
011import org.kuali.ole.describe.bo.DocumentTreeNode;
012import org.kuali.ole.describe.form.EditorForm;
013import org.kuali.ole.describe.form.WorkBibMarcForm;
014import org.kuali.ole.describe.form.WorkInstanceOlemlForm;
015import org.kuali.ole.docstore.discovery.service.QueryService;
016import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
017import org.kuali.ole.docstore.model.bo.WorkBibDocument;
018import org.kuali.ole.docstore.model.bo.WorkHoldingsDocument;
019import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
020import org.kuali.ole.docstore.model.bo.WorkItemDocument;
021import org.kuali.ole.docstore.model.enums.DocType;
022import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
023import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.*;
024import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
025import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
026import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
027import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkInstanceOlemlRecordProcessor;
028import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
029import org.kuali.ole.describe.bo.InstanceEditorFormDataHandler;
030import org.kuali.ole.describe.bo.MarcEditorControlField;
031import org.kuali.ole.describe.bo.MarcEditorDataField;
032import org.kuali.ole.describe.form.InstanceEditorForm;
033import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
034import org.kuali.ole.describe.service.DiscoveryHelperService;
035import org.kuali.ole.describe.service.DocstoreHelperService;
036import org.kuali.ole.select.businessobject.OleCopy;
037import org.kuali.rice.core.api.util.tree.Node;
038import org.kuali.rice.kim.api.permission.PermissionService;
039import org.kuali.rice.kim.api.services.KimApiServiceLocator;
040import org.kuali.rice.krad.service.BusinessObjectService;
041import org.kuali.rice.krad.service.KRADServiceLocator;
042import org.kuali.rice.krad.uif.UifParameters;
043import org.kuali.rice.krad.util.GlobalVariables;
044import org.kuali.rice.krad.util.KRADConstants;
045import org.kuali.rice.krad.web.form.UifFormBase;
046import org.springframework.validation.BindingResult;
047import org.springframework.web.bind.annotation.ModelAttribute;
048import org.springframework.web.bind.annotation.RequestMapping;
049import org.springframework.web.bind.annotation.RequestMethod;
050import org.springframework.web.servlet.ModelAndView;
051
052import javax.servlet.http.HttpServletRequest;
053import javax.servlet.http.HttpServletResponse;
054import javax.xml.datatype.DatatypeConfigurationException;
055import javax.xml.datatype.DatatypeFactory;
056import javax.xml.datatype.XMLGregorianCalendar;
057import java.text.Format;
058import java.text.SimpleDateFormat;
059import java.util.*;
060
061
062/**
063 * Created with IntelliJ IDEA.
064 * User: pp7788
065 * Date: 12/11/12
066 * Time: 2:38 PM
067 * To change this template use File | Settings | File Templates.
068 */
069
070/**
071 * InstanceEditorController is the controller class for Instance Editor
072 */
073//@Controller
074//@RequestMapping(value = "/instanceeditor")
075public class WorkInstanceOlemlEditor
076        extends AbstractEditor
077        implements DocumentEditor {
078
079    private static final Logger LOG = Logger.getLogger(WorkInstanceOlemlEditor.class);
080
081    private DocstoreHelperService docstoreHelperService;
082    private InstanceEditorFormDataHandler instanceEditorFormDataHandler;
083    private DiscoveryHelperService discoveryHelperService;
084
085
086    private static WorkInstanceOlemlEditor workInstanceOlemlEditor = new WorkInstanceOlemlEditor();
087
088    public static WorkInstanceOlemlEditor getInstance() {
089        return workInstanceOlemlEditor;
090    }
091
092    private WorkInstanceOlemlEditor() {
093    }
094
095    private boolean canCreateInstance(String principalId) {
096        PermissionService service = KimApiServiceLocator.getPermissionService();
097        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_ADD_INSTANCE);
098    }
099
100    private boolean canCreateItem(String principalId) {
101        PermissionService service = KimApiServiceLocator.getPermissionService();
102        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_ADD_ITEM);
103    }
104
105    private boolean canEditInstance(String principalId) {
106        PermissionService service = KimApiServiceLocator.getPermissionService();
107        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_EDIT_INSTANCE);
108    }
109
110    private boolean canEditItem(String principalId) {
111        PermissionService service = KimApiServiceLocator.getPermissionService();
112        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_EDIT_ITEM);
113    }
114
115    @Override
116    public EditorForm loadDocument(EditorForm editorForm) {
117        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
118        String docId = editorForm.getDocId();
119        String bibId = editorForm.getBibId();
120        workInstanceOlemlForm.setBibId(bibId);
121        String docType = editorForm.getDocType();
122        editorForm.setHasLink(true);
123        if ((StringUtils.isBlank(editorForm.getTitle()))) {
124            getTitleInfo(editorForm);
125        }
126        if (editorForm.isFromDublin()) {
127            editorForm.setHasLink(false);
128        }
129        if (editorForm.getTitle().contains("<")) {
130            String title = org.apache.commons.lang.StringEscapeUtils.escapeHtml((editorForm.getTitle()));
131            editorForm.setTitle(title);
132        }
133        editorForm.setShowEditorFooter(true);
134        // Modified title display for left pane when Holdings/Item record is added or updated
135        if (docType.equals(DocType.HOLDINGS.getCode()) || docType.equals(DocType.INSTANCE.getCode())) {
136            editorForm.setHeaderText("Instance Editor (Holdings) - OLEML Format");
137        } else if (docType.equals(DocType.ITEM.getCode())) {
138            editorForm.setHeaderText("Instance Editor (Item) - OLEML Format");
139        }
140        List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
141        String callNumberFlag = StringUtils.trimToEmpty(editorForm.getCallNumberFlag());
142        /**
143         * Added if condition for the screen 'Call Number Browse'.
144         * Populating list of workBibDocuments when call number link is clicked.
145         * This is for handling left pane.
146         */
147        if (callNumberFlag.equals("true")) {
148            workBibDocumentList = null;
149        }
150        if (null != bibId && bibId.length() > 0) {
151            workBibDocumentList = new ArrayList<WorkBibDocument>();
152            WorkBibDocument workBibDocument = new WorkBibDocument();
153            workBibDocument.setId(bibId);
154            workBibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument);
155            workBibDocumentList.add(workBibDocument);
156            editorForm.setWorkBibDocumentList(workBibDocumentList);
157            editorForm.setStaffOnlyFlagForBib(Boolean.valueOf(workBibDocument.getStaffOnlyFlag()));
158            /*
159            if (workBibDocumentList == null || workBibDocumentList.size() < 0) {
160                workBibDocumentList = new ArrayList<WorkBibDocument>();
161                WorkBibDocument workBibDocument = new WorkBibDocument();
162                workBibDocument.setId(bibId);
163                workBibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument);
164                workBibDocumentList.add(workBibDocument);
165                editorForm.setWorkBibDocumentList(workBibDocumentList);
166            } else {
167                int count = 0;
168                for (WorkBibDocument bibDocument : workBibDocumentList) {
169                    if (bibDocument.getId() != null) {
170                        if (!bibDocument.getId().equals(bibId)) {
171                            count += 1;
172                        }
173                    }
174                }
175                if (workBibDocumentList.size() == count) {
176                    WorkBibDocument workBibDocument = new WorkBibDocument();
177                    workBibDocument.setId(bibId);
178                    workBibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument);
179                    workBibDocumentList.add(workBibDocument);
180                    editorForm.setWorkBibDocumentList(workBibDocumentList);
181                }
182            }
183*/
184            try {
185                String bibData = getDocstoreHelperService().getDocstoreData(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), bibId);
186                if (isValidBib(bibData)) {
187                    if (null != docId && !docId.equalsIgnoreCase("null") && docId.length() > 0) {
188                        if (workInstanceOlemlForm.getInstanceId() != null
189                                && workInstanceOlemlForm.getInstanceId().length() > 0) {
190                            String docStoreData = getDocstoreHelperService()
191                                    .getDocstoreData(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), workInstanceOlemlForm.getInstanceId());
192                            InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor()
193                                    .fromXML(docStoreData);
194                            workInstanceOlemlForm.setInstance(instanceCollection.getInstance().get(0));
195                            //workInstanceOlemlForm.setMessage("Record loaded successfully.");
196                            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.load.message");
197                        }
198                        try {
199                            List<WorkInstanceDocument> workInstanceDocuments = workBibDocument
200                                    .getWorkInstanceDocumentList();
201                            // String docStoreData = getDocstoreHelperService().getDocstoreData(editorForm.getDocCategory(),editorForm.getDocType(),editorForm.getDocFormat(),docId);
202                            ResponseDocument responseDocument = getDocstoreHelperService()
203                                    .checkOutDocument(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), docId);
204                            String docStoreData = responseDocument.getContent().getContent();
205                            if (docType.equalsIgnoreCase("holdings")) {
206
207
208                                OleHoldings oleHoldings = new WorkHoldingOlemlRecordProcessor().fromXML(docStoreData);
209                                AdditionalAttributes additionalAttributes = responseDocument.getAdditionalAttributes();
210                                editorForm.setStaffOnlyFlagForHoldings(Boolean.valueOf(additionalAttributes.getAttribute(AdditionalAttributes.STAFFONLYFLAG)));
211                                if (workInstanceDocuments != null) {
212                                    for (WorkInstanceDocument workInstanceDocument : workInstanceDocuments) {
213                                        if (workInstanceDocument != null && responseDocument.getUuid().equals
214                                                (workInstanceDocument.getHoldingsDocument()
215                                                        .getHoldingsIdentifier())) {
216                                            editorForm.setHoldingCreatedDate(workInstanceDocument.getHoldingsDocument().getDateEntered());
217                                            editorForm.setHoldingCreatedBy(workInstanceDocument.getHoldingsDocument().getCreatedBy());
218                                            editorForm.setHoldingUpdatedDate(workInstanceDocument.getHoldingsDocument().getDateUpdated());
219                                            editorForm.setHoldingUpdatedBy(workInstanceDocument.getHoldingsDocument().getUpdatedBy());
220                                            editorForm.setHoldingLocalIdentifier(workInstanceDocument.getHoldingsDocument().getLocalId());
221                                            break;
222                                        }
223                                    }
224                                }
225                                List<ExtentOfOwnership> extentOfOwnerships = ensureAtleastOneExtentOfOwnership(
226                                        oleHoldings.getExtentOfOwnership());
227                                oleHoldings.setExtentOfOwnership(extentOfOwnerships);
228
229                                List<Note> notes = ensureAtleastOneNote(oleHoldings.getNote());
230                                oleHoldings.setNote(notes);
231
232                                List<Uri> uriList = ensureAtleastOneUri(oleHoldings.getUri());
233                                oleHoldings.setUri(uriList);
234
235                                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
236                                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
237                                workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
238                                //workInstanceOlemlForm.setMessage("Holdings record loaded successfully.");
239                                if (editorForm.getEditable().equalsIgnoreCase("false")) {
240                                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
241                                            "holdings.record.load.message");
242                                } else {
243                                    boolean hasPermission = canEditInstance(GlobalVariables.getUserSession().getPrincipalId());
244                                    if (hasPermission) {
245                                        GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "holdings.record.load.message");
246                                    } else {
247                                        editorForm.setHideFooter(false);
248                                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_INSTANCE);
249                                    }
250                                }
251                            } else if (docType.equalsIgnoreCase("item")) {
252                                String instanceResponseContent = getDocstoreHelperService()
253                                        .getDocstoreData(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), editorForm.getInstanceId());
254                                InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor()
255                                        .fromXML(instanceResponseContent);
256                                AdditionalAttributes additionalAttributes = responseDocument.getAdditionalAttributes();
257                                if (additionalAttributes != null) {
258                                    editorForm.setStaffOnlyFlagForItem(Boolean.valueOf(additionalAttributes.getAttribute(AdditionalAttributes.STAFFONLYFLAG)));
259                                    editorForm.setItemCreatedBy(additionalAttributes.getAttribute
260                                            (AdditionalAttributes.CREATED_BY));
261                                }
262                                for (WorkInstanceDocument workInstanceDocument : workInstanceDocuments) {
263                                    List<WorkItemDocument> workItemDocuments = workInstanceDocument.getItemDocumentList();
264                                    if (workItemDocuments != null) {
265                                        for (WorkItemDocument workItemDocument : workItemDocuments) {
266                                            if (workItemDocument != null && responseDocument.getUuid()
267                                                    .equals(workItemDocument.getItemIdentifier())) {
268                                                editorForm.setItemCreatedDate(workItemDocument.getDateEntered());
269                                                editorForm.setItemCreatedBy(workItemDocument.getCreatedBy());
270                                                editorForm.setItemUpdatedDate(workItemDocument.getDateUpdated());
271                                                editorForm.setItemUpdatedBy(workItemDocument.getUpdatedBy());
272                                                editorForm.setItemLocalIdentifier(workItemDocument.getLocalId());
273                                                break;
274                                            }
275                                        }
276                                    }
277                                }
278                                OleHoldings oleHoldings = instanceCollection.getInstance().get(0).getOleHoldings();
279                                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
280                                Item item = new WorkItemOlemlRecordProcessor().fromXML(docStoreData);
281                                String itemStatus = null;
282                                if (item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null) {
283                                    itemStatus = item.getItemStatus().getCodeValue();
284                                    workInstanceOlemlForm.setOldItemStatus(itemStatus);
285                                }
286/*
287                                String itemProperty = getInstanceEditorFormDataHandler()
288                                        .getParameter(OLEConstants.DESC_NMSPC, OLEConstants.DESC_CMPNT, OLEParameterConstants.ITEM_STATUS_READONLY);
289*/
290                                String itemProperty = getInstanceEditorFormDataHandler()
291                                        .getParameter("OLE-DESC", "Describe", "ITEM_STATUS_READONLY");
292                                String[] itemArray = itemProperty.split(",");
293                                for (String status : itemArray) {
294                                    if (status.equalsIgnoreCase(itemStatus)) {
295                                        workInstanceOlemlForm.setItemStatusNonEditable(true);
296                                        break;
297                                    }
298                                    workInstanceOlemlForm.setItemStatusNonEditable(false);
299                                }
300                                itemProperty = getInstanceEditorFormDataHandler()
301                                        .getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
302
303                                boolean editable = Boolean.valueOf(itemProperty);
304                                workInstanceOlemlForm.setHoldingsDataInItemReadOnly(editable);
305                                /* if(oleHoldings.getCallNumber() != null){
306                                    item.setCallNumber(oleHoldings.getCallNumber());
307                                }*/
308                                List<Note> notes = ensureAtleastOneNote(item.getNote());
309                                item.setNote(notes);
310                                workInstanceOlemlForm.setSelectedItem(item);
311                                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
312                                workInstanceOlemlForm.setViewId("WorkItemViewPage");
313                                //workInstanceOlemlForm.setMessage("Item record loaded successfully.");
314                                if (editorForm.getEditable().equalsIgnoreCase("false")) {
315                                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
316                                            "item.record.load.message");
317                                } else {
318                                    boolean hasPermission = canEditItem(GlobalVariables.getUserSession().getPrincipalId());
319                                    if (hasPermission) {
320                                        GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
321                                    } else {
322                                        editorForm.setHideFooter(false);
323                                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_ITEM);
324                                    }
325                                }
326                            } else {
327                                InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor()
328                                        .fromXML(docStoreData);
329                                OleHoldings oleHoldings = instanceCollection.getInstance().get(0).getOleHoldings();
330                                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
331                                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
332                                workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
333                                //workInstanceOlemlForm.setMessage("Record loaded successfully.");
334                                editorForm.setDocType("holdings");
335                                AdditionalAttributes additionalAttributes = responseDocument.getAdditionalAttributes();
336                                editorForm.setStaffOnlyFlagForHoldings(Boolean.valueOf(additionalAttributes.getAttribute(AdditionalAttributes.STAFFONLYFLAG)));
337
338                                // editorForm.setHoldingCreatedBy(workBibDocument.getWorkInstanceDocumentList().get(0).getHoldingsDocument().getCreatedBy());
339                                //editorForm.setHoldingCreatedDate(workBibDocument.getWorkInstanceDocumentList().get(0).getHoldingsDocument().getDateEntered());
340                                //editorForm.setHoldingLocalIdentifier(workBibDocument.getWorkInstanceDocumentList().get(0).getHoldingsDocument().getLocalId());
341                                for (WorkInstanceDocument workInstanceDocument : workInstanceDocuments) {
342                                    if (workInstanceDocument != null && responseDocument.getUuid().equals
343                                            (workInstanceDocument.getInstanceIdentifier())) {
344                                        editorForm.setHoldingCreatedDate(workInstanceDocument.getHoldingsDocument().getDateEntered());
345                                        editorForm.setHoldingCreatedBy(workInstanceDocument.getHoldingsDocument().getCreatedBy());
346                                        editorForm.setHoldingUpdatedDate(workInstanceDocument.getHoldingsDocument().getDateUpdated());
347                                        editorForm.setHoldingUpdatedBy(workInstanceDocument.getHoldingsDocument().getUpdatedBy());
348                                        editorForm.setHoldingLocalIdentifier(workInstanceDocument.getHoldingsDocument().getLocalId());
349                                        break;
350                                    }
351                                }
352                                ////////////////////////////////////////////////
353                                List<ExtentOfOwnership> extentOfOwnerships = ensureAtleastOneExtentOfOwnership(
354                                        oleHoldings.getExtentOfOwnership());
355                                oleHoldings.setExtentOfOwnership(extentOfOwnerships);
356
357                                List<Note> notes = ensureAtleastOneNote(oleHoldings.getNote());
358                                oleHoldings.setNote(notes);
359
360                                List<Uri> uriList = ensureAtleastOneUri(oleHoldings.getUri());
361                                oleHoldings.setUri(uriList);
362
363
364                                editorForm.setDocId(instanceCollection.getInstance().get(0).getOleHoldings().getHoldingsIdentifier());
365                                //workInstanceOlemlForm.setMessage("Record loaded successfully.");
366                                if (editorForm.getEditable().equalsIgnoreCase("false")) {
367                                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.load.message");
368                                } else {
369                                    boolean hasPermission = canEditInstance(GlobalVariables.getUserSession().getPrincipalId());
370                                    if (hasPermission) {
371                                        GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "holdings.record.load.message");
372                                    } else {
373                                        editorForm.setHideFooter(false);
374                                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_INSTANCE);
375                                    }
376                                }
377                                //                                if(editorForm.getMessage() == null || editorForm.getMessage().length() == 0)
378                                //                                {
379                                //                                editorForm.setMessage("Please enter details for new Holdings record.");
380                                //                                }
381                                //                                workInstanceOlemlForm.setMessage(editorForm.getMessage());
382
383                            }
384                        } catch (Exception e) {
385//                            workInstanceOlemlForm.setMessage("Error: Could not load Instance record for id:" + docId);
386                            StringBuffer instanceEditorErrorMessage = new StringBuffer(
387                                    OLEConstants.INSTANCE_EDITOR_LOAD_FAILURE).append(" :: \n" + e.getMessage());
388                            //workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
389                            LOG.error(instanceEditorErrorMessage, e);
390                        }
391                    } else {
392                        if ((docType.equalsIgnoreCase("holdings")) || (docType.equalsIgnoreCase("instance"))) {
393                            addHoldingsInformation(editorForm);
394                            editorForm.setStaffOnlyFlagForHoldings(false);
395                            workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
396                            editorForm.setHoldingLocalIdentifier("");
397                            editorForm.setHoldingUpdatedBy("");
398                            editorForm.setHoldingUpdatedDate("");
399
400                            editorForm.setHoldingCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
401                            String createdDate=null;
402                            Format formatter = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
403                            createdDate = formatter.format(new Date());
404                            editorForm.setHoldingCreatedDate(createdDate);
405                            //editorForm.setHoldingCreatedDate(new Date());
406                            //workInstanceOlemlForm.setMessage("Please enter details for new Holdings record.");
407                            boolean hasPermission = canCreateInstance(GlobalVariables.getUserSession().getPrincipalId());
408                            if (hasPermission) {
409                                GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "holdings.record.new.load.message");
410                            } else {
411                                editorForm.setHideFooter(false);
412                                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_CREATE_INSTANCE);
413                            }
414                            //                          if (editorForm.getMessage() == null || editorForm.getMessage().length() == 0) {
415                            //                                editorForm.setMessage("Please enter details for new Holdings record.");
416                            //                            }
417                        } else if (docType.equalsIgnoreCase("item")) {
418                            editorForm.setItemLocalIdentifier("");
419                            editorForm.setItemUpdatedBy("");
420                            editorForm.setItemUpdatedDate("");
421                            editorForm.setItemCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
422                            String createdDate=null;
423                            Format formatter = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
424                            createdDate = formatter.format(new Date());
425                            editorForm.setItemCreatedDate(createdDate);
426                            if ((StringUtils.isNotEmpty(editorForm.getInstanceId())) && !(editorForm.getInstanceId()
427                                    .contains("null"))) {
428                                String docStoreData = getDocstoreHelperService()
429                                        .getDocstoreData(editorForm.getDocCategory(), editorForm.getDocType(), editorForm.getDocFormat(), editorForm.getInstanceId());
430                                InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor()
431                                        .fromXML(docStoreData);
432                                OleHoldings oleHoldings = instanceCollection.getInstance().get(0).getOleHoldings();
433                                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
434                                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
435                                Item item = new Item();
436                                String enumeration = "New";
437                                String chronology = "Item";
438                                String volumeNumber = "Item";
439                                //item.setEnumeration(enumeration);
440                                //item.setChronology(chronology);
441                                item.setVolumeNumber(volumeNumber);
442                                item.setCopyNumber("");
443                                item.setCallNumber(item.getCallNumber());
444                                List<Note> notes = new ArrayList<Note>();
445                                Note note = new Note();
446                                notes.add(note);
447                                item.setNote(notes);
448                                String itemProperty = getInstanceEditorFormDataHandler()
449                                        .getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
450                                String[] itemArray = null;
451                                if (itemProperty != null) {
452                                    itemArray = itemProperty.split(",");
453                                }
454                                if (itemArray != null) {
455                                    for (String status : itemArray) {
456                                        if (status.equalsIgnoreCase("TRUE")) {
457                                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
458                                        } else if (status.equalsIgnoreCase("FALSE")) {
459                                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
460                                        }
461                                    }
462                                }
463
464                                workInstanceOlemlForm.setSelectedItem(item);
465                                workInstanceOlemlForm.setWorkBibDocumentList(editorForm.getWorkBibDocumentList());
466                                this.addItemInformation(editorForm);
467                                editorForm.setStaffOnlyFlagForItem(false);
468                                workInstanceOlemlForm.setViewId("WorkItemViewPage");
469                                //workInstanceOlemlForm.setMessage("Please enter details for new Item record.");
470                                boolean hasPermission = canCreateItem(GlobalVariables.getUserSession().getPrincipalId());
471                                if (hasPermission) {
472                                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
473                                            "item.details.new.message");
474                                } else {
475                                    editorForm.setHideFooter(false);
476                                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_CREATE_ITEM);
477                                }
478                            } else {
479                                OleHoldings oleHoldings = new OleHoldings();
480                                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
481                                workInstanceOlemlForm.setViewId("WorkItemViewPage");
482                            }
483                        }
484                    }
485                } else {
486                    workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
487                    //workInstanceOlemlForm.setMessage("Not valid bib.");
488                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "invalid.bib");
489                }
490            } catch (Exception e) {
491                workInstanceOlemlForm.setMessage("Error: Invalid bibId id:" + bibId);
492                LOG.error("Error:Invalid bibId id:" + bibId + "," + e.getMessage(), e);
493            }
494        } else {
495            workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
496            //workInstanceOlemlForm.setMessage("Not valid bib.");
497            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "invalid.bib");
498        }
499
500        //editorForm.getWorkBibDocumentList();
501        return workInstanceOlemlForm;
502    }
503
504    private void getTitleInfo(EditorForm editorForm) {
505        WorkBibDocument workBibDocument = new WorkBibDocument();
506        workBibDocument.setId(editorForm.getBibId());
507        QueryService queryService = QueryServiceImpl.getInstance();
508        WorkBibDocument document = null;
509        try {
510            document = queryService.buildBibDocumentInfo(workBibDocument);
511        } catch (Exception e) {
512            LOG.error("Failed to get Title / Author details : " + e.getMessage());
513        }
514        StringBuilder titleBuilder = new StringBuilder();
515        titleBuilder.append(document.getTitle());
516        titleBuilder.append("/");
517        if (document.getAuthor() != null) {
518
519            titleBuilder.append(document.getAuthor());
520        }
521        if (workBibDocument.getDocFormat().equalsIgnoreCase("dublinunq")) {
522            editorForm.setFromDublin(true);
523        }
524        editorForm.setTitle(org.apache.commons.lang.StringEscapeUtils.escapeHtml(titleBuilder.toString()));
525    }
526
527    //        private void addItemInformation(EditorForm editorForm) {
528    //            List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
529    //            WorkBibDocument workBibDocument = new WorkBibDocument();
530    //            workBibDocument.setId(editorForm.getBibId());
531    //            workBibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument);
532    //            for (WorkInstanceDocument workInstanceDocument : workBibDocument.getWorkInstanceDocumentList()) {
533    //                if (workInstanceDocument.getInstanceIdentifier().equals(editorForm.getInstanceId())) {
534    //                    WorkItemDocument workItemDocument = new WorkItemDocument();
535    //                    workItemDocument.setBarcode("New Item");
536    //                    if (workInstanceDocument.getItemDocumentList() != null) {
537    //                        workInstanceDocument.getItemDocumentList().add(workItemDocument);
538    //                    }
539    //                    else {
540    //                        List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
541    //                        workItemDocumentList.add(workItemDocument);
542    //                        workInstanceDocument.setItemDocumentList(workItemDocumentList);
543    //                    }
544    //                }
545    //            }
546    //            if (null != workBibDocumentList) {
547    //                boolean isUpdate = false;
548    //                for (WorkBibDocument workBibDocument1 : workBibDocumentList) {
549    //                    if (workBibDocument1.getId().equals(editorForm.getBibId())) {
550    //                        isUpdate = true;
551    //                    }
552    //                }
553    //                if (!isUpdate) {
554    //                    editorForm.getWorkBibDocumentList().add(workBibDocument);
555    //                }
556    //            }
557    //            else {
558    //                List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
559    //                workBibDocuments.add(workBibDocument);
560    //                editorForm.setWorkBibDocumentList(workBibDocuments);
561    //            }
562    //        }
563
564    private void addItemInformation(EditorForm editorForm) {
565        List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
566        WorkBibDocument workBibDocument = new WorkBibDocument();
567        WorkInstanceDocument updatedInstanceDocument = null;
568        WorkBibDocument updateBibDocument = null;
569        boolean isUpdate = false;
570        int indexOfDocument = 0;
571        int i = 0;
572        workBibDocument.setId(editorForm.getBibId());
573        workBibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument);
574        for (WorkInstanceDocument workInstanceDocument : workBibDocument.getWorkInstanceDocumentList()) {
575            if (workInstanceDocument.getInstanceIdentifier().equals(editorForm.getInstanceId())) {
576                WorkItemDocument workItemDocument = new WorkItemDocument();
577                // workItemDocument.setEnumeration("New");
578                //workItemDocument.setChronology("Item");
579                workItemDocument.setCopyNumber("");
580                workItemDocument.setCallNumber("");
581                workItemDocument.setVolumeNumber("Item");
582                if (workInstanceDocument.getItemDocumentList() != null) {
583                    workInstanceDocument.getItemDocumentList().add(workItemDocument);
584                    updatedInstanceDocument = workInstanceDocument;
585                    workBibDocument.setInstanceDocument(updatedInstanceDocument);
586                    updateBibDocument = workBibDocument;
587                    break;
588                } else {
589                    List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
590                    workItemDocumentList.add(workItemDocument);
591                    workInstanceDocument.setItemDocumentList(workItemDocumentList);
592                    updatedInstanceDocument = workInstanceDocument;
593                    workBibDocument.setInstanceDocument(updatedInstanceDocument);
594                    updateBibDocument = workBibDocument;
595                    break;
596                }
597            }
598        }
599
600        for (WorkBibDocument bibDocument : workBibDocumentList) {
601            if (editorForm.getBibId().equals(bibDocument.getId())) {
602                indexOfDocument = i;
603                isUpdate = true;
604                break;
605            }
606            i++;
607        }
608
609        if (isUpdate) {
610            workBibDocumentList.set(indexOfDocument, updateBibDocument);
611            editorForm.getWorkBibDocumentList().set(indexOfDocument, updateBibDocument);
612        } else {
613            List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
614            workBibDocuments.add(workBibDocument);
615            editorForm.setWorkBibDocumentList(workBibDocuments);
616        }
617    }
618
619    private void addHoldingsInformation(EditorForm editorForm) {
620        boolean isUpdated = false;
621        WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument();
622        WorkHoldingsDocument workHoldingsDocument = new WorkHoldingsDocument();
623        workHoldingsDocument.setLocationName("Holdings");
624        workHoldingsDocument.setCallNumber("");
625        workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
626        WorkItemDocument workItemDocument = new WorkItemDocument();
627        //workItemDocument.setEnumeration("New");
628        //workItemDocument.setChronology("Item");
629        workItemDocument.setCopyNumber("");
630        workItemDocument.setCallNumber("");
631        workItemDocument.setVolumeNumber("Item");
632        List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
633        workItemDocumentList.add(workItemDocument);
634        workInstanceDocument.setItemDocumentList(workItemDocumentList);
635
636        for (WorkBibDocument workBibDocument : editorForm.getWorkBibDocumentList()) {
637            if (null != workBibDocument.getId() && workBibDocument.getId().equals(editorForm.getBibId())) {
638
639                if (null != workBibDocument.getWorkInstanceDocumentList()) {
640                    List<WorkInstanceDocument> instanceDocumentList = workBibDocument.getWorkInstanceDocumentList();
641                    for (WorkInstanceDocument instanceDocument : instanceDocumentList) {
642                        if ((instanceDocument.getHoldingsDocument().getLocationName() != null) && (instanceDocument.getHoldingsDocument().getLocationName()
643                                .equalsIgnoreCase(workHoldingsDocument.getLocationName()))) {
644                            instanceDocumentList.remove(instanceDocument);
645                            break;
646                        }
647                    }
648
649                    workBibDocument.getWorkInstanceDocumentList().add(workInstanceDocument);
650                } else {
651                    List<WorkInstanceDocument> workInstanceDocumentList = new ArrayList<WorkInstanceDocument>();
652                    workInstanceDocumentList.add(workInstanceDocument);
653                    workBibDocument.setWorkInstanceDocumentList(workInstanceDocumentList);
654                }
655                isUpdated = true;
656            }
657        }
658        if (!isUpdated) {
659            WorkBibDocument workBibDocument1 = new WorkBibDocument();
660            workBibDocument1.setId(editorForm.getBibId());
661            WorkBibDocument bibDocument = getDocstoreHelperService().getInfoForBibTree(workBibDocument1);
662            if (null != bibDocument.getWorkInstanceDocumentList()) {
663                bibDocument.getWorkInstanceDocumentList().add(workInstanceDocument);
664            } else {
665                List<WorkInstanceDocument> workInstanceDocumentList = new ArrayList<WorkInstanceDocument>();
666                workInstanceDocumentList.add(workInstanceDocument);
667                bibDocument.setWorkInstanceDocumentList(workInstanceDocumentList);
668            }
669            editorForm.getWorkBibDocumentList().add(bibDocument);
670        }
671    }
672
673    private void updateTreeData(EditorForm editorForm) {
674        int indexOfDocument = 0;
675        List<WorkBibDocument> workBibDocumentList = editorForm.getWorkBibDocumentList();
676        int i = 0;
677        for (WorkBibDocument bibDocument : workBibDocumentList) {
678            if (editorForm.getBibId() != null && editorForm.getBibId().equals(bibDocument.getId())) {
679                indexOfDocument = i;
680                break;
681            }
682            i++;
683        }
684        DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
685        WorkBibDocument workBibDocument = new WorkBibDocument();
686        workBibDocument.setId(editorForm.getBibId());
687        workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument);
688        if (workBibDocument.getWorkInstanceDocumentList() != null && workBibDocument.getWorkInstanceDocumentList().size() > 0) {
689            workBibDocumentList.set(indexOfDocument, workBibDocument);
690        } else {
691            workBibDocumentList.remove(indexOfDocument);
692        }
693        editorForm.setWorkBibDocumentList(workBibDocumentList);
694    }
695
696
697    private boolean isValidBib(String bibData) {
698        if (bibData.contains("collection") || bibData.contains("OAI-PMH")) {
699            return true;
700        }
701        return false;
702    }
703
704    @Override
705    public EditorForm saveDocument(EditorForm editorForm) {
706        //        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm)loadDocument(editorForm);
707
708        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
709        String responseFromDocstore = null;
710        String docId = editorForm.getDocId();
711        String docType = editorForm.getDocType();
712        String editorStatusMessage = "";
713        Response dsResponse = new Response();
714        // Boolean staffOnlyFlag=editorForm.isStaffOnlyFlag();
715        AdditionalAttributes additionalAttributes = new AdditionalAttributes();
716
717        try {
718            if (docId != null && "" != docId.trim() && !docId.equalsIgnoreCase("null") && docId.length() > 0) {
719                if (OLEConstants.HOLDING_DOC_TYPE.equalsIgnoreCase(docType)) {
720                    OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
721                    if (!isValidHoldingsData(workInstanceOlemlForm)) {
722                        return workInstanceOlemlForm;
723                    }
724                    String holdingId = workInstanceOlemlForm.getSelectedHolding().getHoldingsIdentifier();
725                    String holdingXmlContent = getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
726                    additionalAttributes.setAttribute(AdditionalAttributes.STAFFONLYFLAG, String.valueOf(editorForm.isStaffOnlyFlagForHoldings()));
727                    additionalAttributes.setAttribute(AdditionalAttributes.CREATED_BY, editorForm.getCreatedBy());
728                    additionalAttributes.setAttribute(AdditionalAttributes.HOLDINGS_CREATED_BY,editorForm.getHoldingCreatedBy());
729                    additionalAttributes.setAttribute(AdditionalAttributes.HOLDINGS_DATE_ENTERED,editorForm.getHoldingCreatedDate());
730                    additionalAttributes.setAttribute(AdditionalAttributes.HOLDINGS_UPDATED_BY,GlobalVariables.getUserSession().getPrincipalName());
731                    String holdingsCreatedDate=null;
732                    Format formatter = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
733                    holdingsCreatedDate = formatter.format(new Date());
734                    additionalAttributes.setAttribute(AdditionalAttributes.HOLDINGS_LAST_UPDATED,holdingsCreatedDate);
735
736                    String holdingRecordUpdateResponse = getDocstoreHelperService()
737                            .updateInstanceRecord(holdingId, OLEConstants.HOLDING_DOC_TYPE, holdingXmlContent, additionalAttributes);
738                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
739                    dsResponse = new ResponseHandler().toObject(holdingRecordUpdateResponse);
740                    if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus()) || "Failed".equalsIgnoreCase(dsResponse.getStatus())) {
741                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
742                                "docstore.response", dsResponse.getStatusMessage());
743                    } else {
744                        //editorStatusMessage = "Holdings record updated successfully.";
745                        editorStatusMessage = "holdings.record.update.message";
746                    }
747                    workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
748
749                } else if (OLEConstants.ITEM_DOC_TYPE.equalsIgnoreCase(docType)) {
750                    Item itemData = workInstanceOlemlForm.getSelectedItem();
751                    OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
752                    workInstanceOlemlForm.setViewId("WorkItemViewPage");
753                    if (!isValidItemData(workInstanceOlemlForm)) {
754                        return workInstanceOlemlForm;
755                    }
756                    String ItemId = workInstanceOlemlForm.getSelectedItem().getItemIdentifier();
757                    String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(itemData);
758                    getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
759                    additionalAttributes.setAttribute(AdditionalAttributes.STAFFONLYFLAG, String.valueOf(editorForm.isStaffOnlyFlagForItem()));
760                    additionalAttributes.setAttribute(AdditionalAttributes.CREATED_BY, editorForm.getCreatedBy());
761                    String itemRecordUpdateResponse = getDocstoreHelperService()
762                            .updateInstanceRecord(ItemId, OLEConstants.ITEM_DOC_TYPE, itemXmlContent, additionalAttributes);
763                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
764                    dsResponse = new ResponseHandler().toObject(itemRecordUpdateResponse);
765                    //                        workInstanceOlemlForm.setMessage("Item record updated successfully.");
766
767                    if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus()) || "Failed".equalsIgnoreCase(dsResponse.getStatus())) {
768                        //editorStatusMessage = "<font size='3' color='red'>" + dsResponse.getStatusMessage() + "</font>";
769                        //workInstanceOlemlForm.setMessage(editorStatusMessage);
770                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
771                                "docstore.response", dsResponse.getStatusMessage());
772
773                        return workInstanceOlemlForm;
774                    } else {
775                        //editorStatusMessage = "Item record updated successfully.";
776                        if (GlobalVariables.getMessageMap().getErrorMessages().isEmpty())
777                            editorStatusMessage = "item.record.update.message";
778                    }
779
780                    String itemProperty = getInstanceEditorFormDataHandler()
781                            .getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
782                    String[] itemArray = null;
783                    if (itemProperty != null) {
784                        itemArray = itemProperty.split(",");
785                    }
786                    for (String status : itemArray) {
787                        if (status.equalsIgnoreCase("TRUE")) {
788                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
789                        } else if (status.equalsIgnoreCase("FALSE")) {
790                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
791                        }
792                    }
793                    if (!isValidHoldingsData(workInstanceOlemlForm)) {
794                        return workInstanceOlemlForm;
795                    }
796                    String holdingId = workInstanceOlemlForm.getSelectedHolding().getHoldingsIdentifier();
797                    String holdingXmlContent = getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
798                    getInstanceEditorFormDataHandler().buildItemContent(itemData);
799                    AdditionalAttributes additionalAttributesForHoldings = new AdditionalAttributes();
800                    additionalAttributesForHoldings.setAttribute(AdditionalAttributes.STAFFONLYFLAG, String.valueOf(editorForm.isStaffOnlyFlagForHoldings()));
801                    additionalAttributesForHoldings.setAttribute(AdditionalAttributes.CREATED_BY, editorForm.getCreatedBy());
802                    String holdingRecordUpdateResponse = getDocstoreHelperService()
803                            .updateInstanceRecord(holdingId, OLEConstants.HOLDING_DOC_TYPE, holdingXmlContent, additionalAttributesForHoldings);
804                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
805                    dsResponse = new ResponseHandler().toObject(holdingRecordUpdateResponse);
806                    if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus()) || "Failed".equalsIgnoreCase(dsResponse.getStatus())) {
807                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
808                                "docstore.response", dsResponse.getStatusMessage());
809                    }
810                }
811
812                updateTreeData(editorForm);
813
814                if (workInstanceOlemlForm.getInstance() != null
815                        && workInstanceOlemlForm.getInstance().getSourceHoldings() != null) {
816                    SourceHoldings sourceHoldings = getInstanceEditorFormDataHandler()
817                            .buildSourceHoldings(workInstanceOlemlForm);
818                    String sourceHoldingId = sourceHoldings.getHoldingsIdentifier();
819                    String sourceHoldinXml = getInstanceEditorFormDataHandler()
820                            .buildSourceHoldingContent(sourceHoldings);
821                    String sourceHoldingUpdateResponse = getDocstoreHelperService()
822                            .updateInstanceRecord(sourceHoldingId, "sourceHoldings", sourceHoldinXml);
823                    dsResponse = new ResponseHandler().toObject(sourceHoldingUpdateResponse);
824                }
825                //                editorStatusMessage = new String(OLEConstants.INSTANCE_EDITOR_SUCCESS);
826            } else {
827                Instance instance = new Instance();
828                if (editorForm.getBibId() != null) {
829                    instance.setResourceIdentifier(Arrays.asList(editorForm.getBibId()));
830                }
831                workInstanceOlemlForm.setInstance(instance);
832                Item oleItem = workInstanceOlemlForm.getSelectedItem();
833                OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
834                /* if (workInstanceOlemlForm != null && workInstanceOlemlForm.getSelectedHolding() != null
835                            && workInstanceOlemlForm.getSelectedHolding().getCallNumber() != null && oleItem != null){
836                    oleItem.setCallNumber(workInstanceOlemlForm.getSelectedHolding().getCallNumber());
837                }*/
838                Items items = new Items();
839                if(docType.equalsIgnoreCase(OLEConstants.ITEM_DOC_TYPE)) {
840                    items.setItem(Arrays.asList(workInstanceOlemlForm.getSelectedItem()));
841                }
842                else {
843                    items.setItem(Arrays.asList(oleItem));
844                }
845                workInstanceOlemlForm.getInstance().setItems(items);
846                workInstanceOlemlForm.getSelectedHolding().setPrimary("true");
847
848                workInstanceOlemlForm.getInstance().setOleHoldings(workInstanceOlemlForm.getSelectedHolding());
849                if (docType.equalsIgnoreCase(OLEConstants.INSTANCE_DOC_TYPE) || StringUtils.isEmpty(editorForm.getInstanceId())) {
850                    if (!isValidHoldingsData(workInstanceOlemlForm)) {
851                        return workInstanceOlemlForm;
852                    }
853                    String staffOnlyFlagForHoldings = String.valueOf(editorForm.isStaffOnlyFlagForHoldings());
854
855                    String content = getInstanceEditorFormDataHandler()
856                            .buildInstanceRecordForDocStore(workInstanceOlemlForm, docId, staffOnlyFlagForHoldings);
857                    responseFromDocstore = getDocstoreHelperService().
858                            instanceRecordCallToDocstore(content, null, OLEConstants.OLEML_FORMAT);
859                    dsResponse = new ResponseHandler().toObject(responseFromDocstore);
860                    if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus()) || "Failed".equalsIgnoreCase(dsResponse.getStatus())) {
861                        getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
862                        //editorStatusMessage = "<font size='3' color='red'>" + dsResponse.getStatusMessage() + "</font>";
863                        //workInstanceOlemlForm.setMessage(editorStatusMessage);
864                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
865                                "docstore.response", dsResponse.getStatusMessage());
866
867                        return workInstanceOlemlForm;
868                    } else {
869                        //editorStatusMessage = "Record created successfully .";
870                        editorStatusMessage = "record.create.message";
871                    }
872                } else if (docType.equalsIgnoreCase(OLEConstants.ITEM_DOC_TYPE)) {
873                    if (!isValidItemData(workInstanceOlemlForm)) {
874                        return workInstanceOlemlForm;
875                    }
876                    /* AdditionalAttributes additionalAttributesForItem = new AdditionalAttributes();
877                                        additionalAttributesForItem.setAttribute(AdditionalAttributes.STAFFONLYFLAG,String.valueOf(editorForm.isStaffOnlyFlagForItem()));
878                    */
879                    /*Map<String, String> mapObject = new HashMap<String, String>();
880                    mapObject.put("staffOnlyFlag", String.valueOf(editorForm.isStaffOnlyFlagForItem()));*/
881                    String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
882
883                    String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
884                    getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
885                    responseFromDocstore = getDocstoreHelperService().
886                            createItemForInstanceRecord(editorForm.getInstanceId(), OLEConstants.ITEM_DOC_TYPE,
887                                    itemXmlContent);
888
889                    dsResponse = new ResponseHandler().toObject(responseFromDocstore);
890                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
891
892                    if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus()) || "Failed".equalsIgnoreCase(dsResponse.getStatus())) {
893                        //editorStatusMessage = "<font size='3' color='red'>" + dsResponse.getStatusMessage() + "</font>";
894                        //workInstanceOlemlForm.setMessage(editorStatusMessage);
895                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
896                                "docstore.response", dsResponse.getStatusMessage());
897
898                        return workInstanceOlemlForm;
899                    } else {
900                        //editorStatusMessage = "Record created successfully.";
901                        if (GlobalVariables.getMessageMap().getErrorMessages().isEmpty())
902                            editorStatusMessage = "record.create.message";
903                    }
904                }
905                //Refreshing Editor after creating new instance record to load created instance uuid.
906                dsResponse = new ResponseHandler().toObject(responseFromDocstore);
907                String validationMsg = null;
908                if (dsResponse.getStatus().toLowerCase().contains(OLEConstants.OLE_DOCSTORE_RESPONSE_STATUS)) {
909                    String responseUUID = dsResponse.getDocuments().get(0).getUuid();
910                    validationMsg = dsResponse.getDocuments().get(0).getStatusMessage();
911                    workInstanceOlemlForm.setUuid(responseUUID);
912                    if (docType.equalsIgnoreCase(OLEConstants.ITEM_DOC_TYPE)) {
913                        if(StringUtils.isEmpty(editorForm.getInstanceId())){
914                            editorForm.setInstanceId(responseUUID);
915                            editorForm.setDocId(dsResponse.getDocuments().get(0).getLinkedDocuments().get(1).getUuid());
916                        }
917                        else {
918                            editorForm.setDocId(dsResponse.getDocuments().get(0).getLinkedDocuments().get(0).getUuid());
919                        }
920                    } else {
921                        editorForm.setDocId(dsResponse.getDocuments().get(0).getUuid());
922                    }
923                    if (!StringUtils.isEmpty(validationMsg)) {
924                        editorStatusMessage = editorStatusMessage + " : " + validationMsg;
925                    }
926                    //                    String instCol = docstoreHelperService.getDocstoreData(responseUUID);
927                    updateTreeData(editorForm);
928                    /* WorkInstanceOlemlRecordProcessor instRecordProc = new WorkInstanceOlemlRecordProcessor();
929                    InstanceCollection instCollection =  instRecordProc.fromXML(instCol);
930                    String itemUuid = instCollection.getInstance().get(0).getItems().getItem().get(0).getItemIdentifier();
931                    editorForm.setDocId(itemUuid);
932                    editorForm.setDocType(OLEConstants.ITEM_DOC_TYPE);
933                    loadDocument(editorForm);*/
934                    //                    workInstanceOlemlForm.setViewId("WorkItemViewPage");
935                } else {
936                    if (!StringUtils.isEmpty(validationMsg)) {
937                        editorStatusMessage = OLEConstants.INSTANCE_EDITOR_FAILURE + " : " + validationMsg;
938                    } else {
939                        if (StringUtils.isEmpty(editorStatusMessage)) {
940                            //editorStatusMessage = OLEConstants.INSTANCE_EDITOR_FAILURE;
941                            editorStatusMessage = "record.submit.fail.message";
942
943                        }
944                    }
945
946                }
947            }
948            //            editorForm.setMessage(editorStatusMessage);
949        } catch (Exception e) {
950            LOG.error("Exception:" + e.getMessage(), e);
951            StringBuffer instanceEditorErrorMessage = new StringBuffer(OLEConstants.INSTANCE_EDITOR_FAILURE)
952                    .append(" :: \n" + e.getMessage());
953            //workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
954            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "docstore.response",
955                    instanceEditorErrorMessage.toString());
956            LOG.error(instanceEditorErrorMessage);
957        }
958        //        return loadDocument(editorForm);
959        if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus())) {
960            //workInstanceOlemlForm.setMessage(editorStatusMessage);
961            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorStatusMessage);
962        } else {
963            workInstanceOlemlForm = (WorkInstanceOlemlForm) loadDocument(editorForm);
964            //workInstanceOlemlForm.setMessage(editorStatusMessage);
965            GlobalVariables.getMessageMap().getInfoMessages().clear();
966            if (!StringUtils.isEmpty(editorStatusMessage)) {
967
968                GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorStatusMessage);
969            }
970        }
971        return workInstanceOlemlForm;
972    }
973
974
975    @Override
976    public EditorForm deleteDocument(EditorForm editorForm) {
977        return new WorkBibMarcForm();
978    }
979
980    @Override
981    public EditorForm createNewRecord(EditorForm editorForm, Request request) {
982
983        if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
984            editorForm.setNeedToCreateInstance(true);
985        }
986        editNewRecord(editorForm, request);
987        return editorForm.getDocumentForm();
988    }
989
990
991    @Override
992    public EditorForm editNewRecord(EditorForm editorForm, Request request) {
993        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
994        if ((editorForm.getDocumentForm() instanceof WorkInstanceOlemlForm)) {
995            workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
996            workInstanceOlemlForm.setViewId(editorForm.getDocumentForm().getViewId());
997        }
998
999        workInstanceOlemlForm.setDocCategory("work");
1000        workInstanceOlemlForm.setDocType("instance");
1001        workInstanceOlemlForm.setDocFormat("oleml");
1002
1003        if (request.getRequestDocuments() != null && request.getRequestDocuments().size() > 0) {
1004            for (RequestDocument reqDoc : request.getRequestDocuments()) {
1005                for (RequestDocument linkedReqDoc : reqDoc.getLinkedRequestDocuments()) {
1006                    if (linkedReqDoc != null && linkedReqDoc.getContent() != null
1007                            && linkedReqDoc.getContent().getContent() != null) {
1008                        String instContent = linkedReqDoc.getContent().getContent();
1009                        InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor()
1010                                .fromXML(instContent);
1011                        if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
1012                            editorForm.setHeaderText("Import Bib Step-4 Instance Editor (Item)- OLEML Format");
1013                            // validate user entered holding data before going to item tab
1014                            if (!isValidHoldingsData(workInstanceOlemlForm)) {
1015                                return workInstanceOlemlForm;
1016                            }
1017                            instanceCollection.getInstance().get(0)
1018                                    .setOleHoldings(workInstanceOlemlForm.getSelectedHolding());
1019                            WorkInstanceOlemlRecordProcessor olemlReocordProcessor
1020                                    = new WorkInstanceOlemlRecordProcessor();
1021                            String holContent = olemlReocordProcessor.toXML(instanceCollection);
1022                            Map<String, String> mapObject = new HashMap<String, String>();
1023                            mapObject.put("staffOnlyFlag", String.valueOf(editorForm.isStaffOnlyFlagForHoldings()));
1024                            mapObject.put("createdBy", GlobalVariables.getUserSession().getPrincipalName());
1025                            AdditionalAttributes additionalAttributes = new AdditionalAttributes();
1026                            additionalAttributes.setAttributeMap(mapObject);
1027                            linkedReqDoc.setAdditionalAttributes(additionalAttributes);
1028                            linkedReqDoc.getContent().setContent(holContent);
1029                            List<RequestDocument> reqDocList = new ArrayList<RequestDocument>();
1030                            reqDocList.add(linkedReqDoc);
1031                            reqDoc.setLinkedRequestDocuments(reqDocList);
1032                            Item item = instanceCollection.getInstance().get(0).getItems().getItem().get(0);
1033                            List<Note> notes = ensureAtleastOneNote(item.getNote());
1034                            item.setNote(notes);
1035                            workInstanceOlemlForm.setSelectedItem(item);
1036                            workInstanceOlemlForm.setViewId("WorkItemViewPage");
1037                            //workInstanceOlemlForm.setMessage("Please enter details for new Item record.");
1038                            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
1039                                    "item.details.new.message");
1040                        } else if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkBibEditorViewPage")) {
1041                            editorForm.setHeaderText("Import Bib Step-4 Instance Editor (Holdings)- OLEML Format");
1042                            workInstanceOlemlForm.setViewId("WorkHoldingsViewPage");
1043                            //workInstanceOlemlForm.setMessage("Please enter details for new Holdings record.");
1044                            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
1045                                    "holdings.record.new.load.message");
1046                            workInstanceOlemlForm
1047                                    .setSelectedHolding(instanceCollection.getInstance().get(0).getOleHoldings());
1048                        } else if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkItemViewPage")) {
1049                            if (!isValidItemData(workInstanceOlemlForm)) {
1050                                return workInstanceOlemlForm;
1051                            }
1052                            String instanceCol = request.getRequestDocuments().get(0).getLinkedRequestDocuments().get(0)
1053                                    .getContent().getContent();
1054                            WorkInstanceOlemlRecordProcessor recProcessor = new WorkInstanceOlemlRecordProcessor();
1055                            InstanceCollection instCol = recProcessor.fromXML(instanceCol);
1056                            Item item = workInstanceOlemlForm.getSelectedItem();
1057                            Map<String, String> mapObject = new HashMap<String, String>();
1058                            String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
1059                            try {
1060                                String holdingXmlContent = getInstanceEditorFormDataHandler()
1061                                        .buildHoldingContent(workInstanceOlemlForm.getSelectedHolding());
1062                                WorkHoldingOlemlRecordProcessor holdingRecordProcessor
1063                                        = new WorkHoldingOlemlRecordProcessor();
1064                                OleHoldings holding = holdingRecordProcessor.fromXML(holdingXmlContent);
1065                                instCol.getInstance().get(0).setOleHoldings(holding);
1066                                String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(item, staffOnlyFlagForItem);
1067                                WorkItemOlemlRecordProcessor itemProcessor = new WorkItemOlemlRecordProcessor();
1068                                item = itemProcessor.fromXML(itemXmlContent);
1069                            } catch (Exception e) {
1070                                StringBuffer instanceEditorErrorMessage = new StringBuffer(
1071                                        OLEConstants.INSTANCE_EDITOR_FAILURE).append(" :: \n" + e.getMessage());
1072                                workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
1073                                LOG.error(instanceEditorErrorMessage);
1074                            }
1075                            List<Item> items = new ArrayList<Item>();
1076                            items.add(item);
1077                            instCol.getInstance().get(0).getItems().setItem(items);
1078                            instanceCol = recProcessor.toXML(instCol);
1079                            request.getRequestDocuments().get(0).getLinkedRequestDocuments().get(0).getContent()
1080                                    .setContent(instanceCol);
1081                        }
1082
1083                    }
1084                }
1085
1086            }
1087
1088        }
1089        editorForm.setDocumentForm(workInstanceOlemlForm);
1090        return editorForm;
1091    }
1092
1093    @Override
1094    public String saveDocument(Request req, EditorForm editorForm) {
1095        String responseFromDocstore = null;
1096        String editorStatusMessage = "";
1097        Response dsResponse = new Response();
1098        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1099        if (req != null) {
1100            RequestHandler reqHandler = new RequestHandler();
1101            String content = reqHandler.toXML(req);
1102            try {
1103                responseFromDocstore = getDocstoreHelperService()
1104                        .persistToDocstoreFromUnifiedEditor(content, null, null);
1105                dsResponse = new ResponseHandler().toObject(responseFromDocstore);
1106                // Validation messages in editor screen when a record is failed to submit.
1107                if (Response.FAILURE.equalsIgnoreCase(dsResponse.getStatus())||"Failed".equalsIgnoreCase(dsResponse.getStatus())) {
1108                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1109                    //editorStatusMessage = "<font size='3' color='red'>" + dsResponse.getStatusMessage() + "</font>";
1110                    GlobalVariables.getMessageMap()
1111                            .putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, "docstore.response",
1112                                    dsResponse.getStatusMessage());
1113                    workInstanceOlemlForm.setMessage(editorStatusMessage);
1114                }
1115            } catch (Exception e) {
1116                StringBuffer marcEditorErrorMessage = new StringBuffer(OLEConstants.MARC_EDITOR_FAILURE)
1117                        .append("\n" + e.getMessage());
1118                //                responseFromDocstore = marcEditorErrorMessage.toString();
1119                workInstanceOlemlForm.setMessage(marcEditorErrorMessage.toString());
1120
1121            }
1122        }
1123        editorForm.setDocumentForm(workInstanceOlemlForm);
1124        return responseFromDocstore;
1125    }
1126
1127    /**
1128     * This method creates a instance of InstanceEditorForm
1129     *
1130     * @param httpServletRequest
1131     * @return InstanceEditorForm
1132     */
1133    protected UifFormBase createInitialForm(HttpServletRequest httpServletRequest) {
1134        return new WorkInstanceOlemlForm();
1135    }
1136
1137    /**
1138     * This method takes the initial request when click on InstanceEditor Screen.
1139     *
1140     * @param form
1141     * @param result
1142     * @param request
1143     * @param response
1144     * @return ModelAndView
1145     */
1146    public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1147                              HttpServletRequest request, HttpServletResponse response) {
1148        WorkInstanceOlemlForm instanceEditorForm = (WorkInstanceOlemlForm) form;
1149        //ModelAndView modelAndView = super.start(instanceEditorForm, result, request, response);
1150        // return getUIFModelAndView(instanceEditorForm, "WorkHoldingsViewPage");
1151        return null;
1152    }
1153
1154
1155    /**
1156     * This method will fetch the holding/Item records based on the AdditionalAttributes.
1157     *
1158     * @param form
1159     * @param result
1160     * @param request
1161     * @param response
1162     * @return ModelAndView
1163     */
1164    public ModelAndView load(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1165                             HttpServletRequest request, HttpServletResponse response) {
1166        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) form;
1167        //EditorForm workInstanceOlemlForm = (WorkInstanceOlemlForm) form;
1168        //WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
1169        String uuid = request.getParameter("uuid");
1170        String docType = request.getParameter("docType");
1171        String docFormat = request.getParameter("docFormat");
1172        String docCategory = request.getParameter("docCategory");
1173        if (null == uuid || StringUtils.isEmpty(uuid)) {
1174            uuid = workInstanceOlemlForm.getUuid();
1175        }
1176        workInstanceOlemlForm.setExisting("true");
1177        try {
1178            if (workInstanceOlemlForm.getInstanceId() != null && workInstanceOlemlForm.getInstanceId().length() > 0) {
1179                String docStoreData = getDocstoreHelperService().getDocstoreData(docCategory, docType, docFormat, workInstanceOlemlForm.getInstanceId());
1180                InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor().fromXML(docStoreData);
1181                workInstanceOlemlForm.setInstance(instanceCollection.getInstance().get(0));
1182            }
1183            String docStoreData = getDocstoreHelperService().getDocstoreData(docCategory, docType, docFormat, uuid);
1184            if (docType.equalsIgnoreCase("holdings")) {
1185                OleHoldings oleHoldings = new WorkHoldingOlemlRecordProcessor().fromXML(docStoreData);
1186                workInstanceOlemlForm.setSelectedHolding(oleHoldings);
1187                //return getUIFModelAndView(workInstanceOlemlForm,"WorkHoldingsViewPage");
1188            } else if (docType.equalsIgnoreCase("item")) {
1189                Item item = new WorkItemOlemlRecordProcessor().fromXML(docStoreData);
1190                workInstanceOlemlForm.setSelectedItem(item);
1191                //return getUIFModelAndView(workInstanceOlemlForm, "WorkItemViewPage");
1192            } else {
1193                InstanceCollection instanceCollection = new WorkInstanceOlemlRecordProcessor().fromXML(docStoreData);
1194                workInstanceOlemlForm.setSelectedHolding(instanceCollection.getInstance().get(0).getOleHoldings());
1195                //return getUIFModelAndView(workInstanceOlemlForm,"WorkHoldingsViewPage");
1196            }
1197        } catch (Exception e) {
1198            StringBuffer instanceEditorErrorMessage = new StringBuffer(OLEConstants.INSTANCE_EDITOR_LOAD_FAILURE)
1199                    .append(" :: \n" + e.getMessage());
1200            //workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
1201            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.load.fail.message");
1202            LOG.error(instanceEditorErrorMessage);
1203            //return getUIFModelAndView(workInstanceOlemlForm);
1204        }
1205        return null;
1206    }
1207
1208    /**
1209     * Used for Test-case
1210     *
1211     * @param result
1212     * @param request
1213     * @param response
1214     * @param instanceEditorForm
1215     * @return ModelAndView
1216     */
1217    protected ModelAndView callSuper(BindingResult result, HttpServletRequest request, HttpServletResponse response,
1218                                     InstanceEditorForm instanceEditorForm) {
1219        //return super.updateComponent(instanceEditorForm, result, request, response);
1220        return null;
1221    }
1222
1223    /**
1224     * Gets the docstoreHelperService attribute
1225     *
1226     * @return Returns DocstoreHelperService
1227     */
1228    private DocstoreHelperService getDocstoreHelperService() {
1229        if (null == docstoreHelperService) {
1230            return new DocstoreHelperService();
1231        }
1232        return docstoreHelperService;
1233    }
1234
1235    /**
1236     * Sets the docstoreHelperService attribute values.
1237     *
1238     * @param docstoreHelperService
1239     */
1240    public void setDocstoreHelperService(DocstoreHelperService docstoreHelperService) {
1241        this.docstoreHelperService = docstoreHelperService;
1242    }
1243
1244    /**
1245     * Gets the InstanceEditorFormDataHandler attribute.
1246     *
1247     * @return Returns InstanceEditorFormDataHandler.
1248     */
1249    private InstanceEditorFormDataHandler getInstanceEditorFormDataHandler() {
1250        if (null == instanceEditorFormDataHandler) {
1251            instanceEditorFormDataHandler = new InstanceEditorFormDataHandler();
1252        }
1253        return instanceEditorFormDataHandler;
1254    }
1255
1256    /**
1257     * This method returns AdditionalAttributes instance from the list of Extension.
1258     *
1259     * @param extensionList
1260     * @return AdditionalAttributes
1261     */
1262    private AdditionalAttributes getFirstAdditionalAttributes(List<Extension> extensionList) {
1263        for (Extension ext : extensionList) {
1264            for (Object obj : ext.getContent()) {
1265                if (obj instanceof AdditionalAttributes) {
1266                    return (AdditionalAttributes) obj;
1267                }
1268            }
1269        }
1270        return null;
1271    }
1272
1273    /**
1274     * Sets the discoveryHelperService attribute value.
1275     *
1276     * @param discoveryHelperService
1277     */
1278    public void setDiscoveryHelperService(DiscoveryHelperService discoveryHelperService) {
1279        this.discoveryHelperService = discoveryHelperService;
1280    }
1281
1282    /**
1283     * Gets the discoveryHelperService attribute.
1284     *
1285     * @return Returns DiscoveryHelperService.
1286     */
1287    public DiscoveryHelperService getDiscoveryHelperService() {
1288        if (null == discoveryHelperService) {
1289            return new DiscoveryHelperService();
1290        }
1291        return discoveryHelperService;
1292    }
1293
1294    /*@RequestMapping(params = "methodToCall=addExtentOfOwnership")
1295    public ModelAndView addExtentOfOwnership(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1296                                             HttpServletRequest request, HttpServletResponse response) {
1297        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1298        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1299        index++;
1300        List<ExtentOfOwnership> extentOfOwnershipForUI = instanceEditorForm.getSelectedHolding().getExtentOfOwnership();
1301        extentOfOwnershipForUI.add(index, new ExtentOfOwnership());
1302        return super.updateComponent(instanceEditorForm, result, request, response);
1303    }
1304
1305    @RequestMapping(params = "methodToCall=removeExtentOfOwnership")
1306    public ModelAndView removeExtentOfOwnership(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1307                                                HttpServletRequest request, HttpServletResponse response) {
1308        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1309        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1310        List<ExtentOfOwnership> extentOfOwnershipForUI = instanceEditorForm.getSelectedHolding().getExtentOfOwnership();
1311        if (extentOfOwnershipForUI.size() > 1)
1312            extentOfOwnershipForUI.remove(index);
1313        return super.updateComponent(instanceEditorForm, result, request, response);
1314    }*/
1315
1316    @RequestMapping(params = "methodToCall=addAccessInformation")
1317    public ModelAndView addAccessInformation(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1318                                             HttpServletRequest request, HttpServletResponse response) {
1319        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1320        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1321        index++;
1322        List<Uri> accessInformation = instanceEditorForm.getSelectedHolding().getUri();
1323        accessInformation.add(index, new Uri());
1324        //return super.updateComponent(instanceEditorForm, result, request, response);
1325        return null;
1326    }
1327
1328    @RequestMapping(params = "methodToCall=removeAccessInformation")
1329    public ModelAndView removeAccessInformation(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1330                                                HttpServletRequest request, HttpServletResponse response) {
1331        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1332        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1333        List<Uri> accessInformation = instanceEditorForm.getSelectedHolding().getUri();
1334        if (accessInformation.size() > 1)
1335            accessInformation.remove(index);
1336        //return super.updateComponent(instanceEditorForm, result, request, response);
1337        return null;
1338    }
1339
1340    @RequestMapping(params = "methodToCall=addHoldingNotes")
1341    public ModelAndView addHoldingNotes(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1342                                        HttpServletRequest request, HttpServletResponse response) {
1343        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1344        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1345        index++;
1346        List<Note> holdingsNote = instanceEditorForm.getSelectedHolding().getNote();
1347        holdingsNote.add(index, new Note());
1348        //return super.updateComponent(instanceEditorForm, result, request, response);
1349        return null;
1350    }
1351
1352    @RequestMapping(params = "methodToCall=removeHoldingNotes")
1353    public ModelAndView removeHoldingNotes(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1354                                           HttpServletRequest request, HttpServletResponse response) {
1355        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1356        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1357        List<Note> holdingsNote = instanceEditorForm.getSelectedHolding().getNote();
1358        if (holdingsNote.size() > 1)
1359            holdingsNote.remove(index);
1360        //return super.updateComponent(instanceEditorForm, result, request, response);
1361        return null;
1362    }
1363
1364    /**
1365     * This method will add the controlField record based on the selected Line index and updates the component.
1366     *
1367     * @param form
1368     * @param result
1369     * @param request
1370     * @param response
1371     * @return ModelAndView
1372     */
1373    @RequestMapping(params = "methodToCall=addControlField")
1374    public ModelAndView addControlField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1375                                        HttpServletRequest request, HttpServletResponse response) {
1376        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1377        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1378        index++;
1379        List<MarcEditorControlField> marcEditorControlFieldList = instanceEditorForm.getSelectedSourceHolding()
1380                .getControlFields();
1381        marcEditorControlFieldList.add(index, new MarcEditorControlField());
1382        //return super.updateComponent(instanceEditorForm, result, request, response);
1383        return null;
1384    }
1385
1386    /**
1387     * This method will remove the controlField based on the index position and updates the component.
1388     *
1389     * @param form
1390     * @param result
1391     * @param request
1392     * @param response
1393     * @return ModelAndView
1394     */
1395    @RequestMapping(params = "methodToCall=removeControlField")
1396    public ModelAndView removeControlField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1397                                           HttpServletRequest request, HttpServletResponse response) {
1398        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1399        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1400        List<MarcEditorControlField> editorControlFieldList = instanceEditorForm.getSelectedSourceHolding().getControlFields();
1401        if (editorControlFieldList.size() > 1)
1402            editorControlFieldList.remove(index);
1403        //return super.updateComponent(instanceEditorForm, result, request, response);
1404        return null;
1405    }
1406
1407    /**
1408     * This method will add the datField record based on the selected Line index and updates the component.
1409     *
1410     * @param form
1411     * @param result
1412     * @param request
1413     * @param response
1414     * @return ModelAndView
1415     */
1416    @RequestMapping(params = "methodToCall=addDataField")
1417    public ModelAndView addDataField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1418                                     HttpServletRequest request, HttpServletResponse response) {
1419        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1420        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1421        index++;
1422        List<MarcEditorDataField> editorDataFieldList = instanceEditorForm.getSelectedSourceHolding().getDataFields();
1423        editorDataFieldList.add(index, new MarcEditorDataField());
1424        //return super.updateComponent(instanceEditorForm, result, request, response);
1425        return null;
1426    }
1427
1428    /**
1429     * This method will remove the dataField based on the index position and updates the component.
1430     *
1431     * @param form
1432     * @param result
1433     * @param request
1434     * @param response
1435     * @return ModelAndView
1436     */
1437    @RequestMapping(params = "methodToCall=removeDataField")
1438    public ModelAndView removeDataField(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1439                                        HttpServletRequest request, HttpServletResponse response) {
1440        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1441        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1442        List<MarcEditorDataField> marcEditorDataFieldList = instanceEditorForm.getSelectedSourceHolding().getDataFields();
1443        if (marcEditorDataFieldList.size() > 1)
1444            marcEditorDataFieldList.remove(index);
1445        //return super.updateComponent(instanceEditorForm, result, request, response);
1446        return null;
1447    }
1448
1449    @RequestMapping(method = RequestMethod.POST, params = "methodToCall=deleteItem")
1450    public ModelAndView deleteItem(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1451                                   HttpServletRequest request, HttpServletResponse response) throws Exception {
1452        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1453        String id = instanceEditorForm.getDeleteItemId();
1454        String[] ids = id.split("_");
1455        String itemUuid = ids[0];
1456        String docstoreResponse = getDocstoreHelperService().deleteItemrecord(itemUuid);
1457        Response responseObj = new ResponseHandler().toObject(docstoreResponse);
1458        if (responseObj.getStatus().toLowerCase().contains(OLEConstants.OLE_DOCSTORE_RESPONSE_STATUS)) {
1459            //instanceEditorForm.setMessage(OLEConstants.INSTANCE_EDITOR_DELETE_SUCCESS);
1460            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.delete.message ");
1461        } else {
1462            //instanceEditorForm.setMessage(OLEConstants.INSTANCE_EDITOR_DELETE_FAILURE);
1463            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.delete.fail.message");
1464        }
1465        //return getUIFModelAndView(instanceEditorForm,OLEConstants.HOLDINGS_PAGE);
1466        return null;
1467    }
1468
1469    @RequestMapping(params = "methodToCall=addExtentOfOwnership")
1470    public ModelAndView addExtentOfOwnership(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1471                                             HttpServletRequest request, HttpServletResponse response) {
1472        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1473        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1474        index++;
1475        List<ExtentOfOwnership> extentOfOwnershipForUI = instanceEditorForm.getSelectedHolding().getExtentOfOwnership();
1476        ExtentOfOwnership extentOfOwnership = new ExtentOfOwnership();
1477        extentOfOwnership.getNote().add(new Note());
1478        extentOfOwnershipForUI.add(index, extentOfOwnership);
1479        //        return super.updateComponent(instanceEditorForm, result, request, response);
1480        return null;
1481    }
1482
1483    @RequestMapping(params = "methodToCall=removeExtentOfOwnership")
1484    public ModelAndView removeExtentOfOwnership(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1485                                                HttpServletRequest request, HttpServletResponse response) {
1486        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1487        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1488        List<ExtentOfOwnership> extentOfOwnershipForUI = instanceEditorForm.getSelectedHolding().getExtentOfOwnership();
1489        if (extentOfOwnershipForUI.size() > 1) {
1490            extentOfOwnershipForUI.remove(index);
1491        }
1492        //        return super.updateComponent(instanceEditorForm, result, request, response);
1493        return null;
1494    }
1495
1496    @RequestMapping(params = "methodToCall=addEOWHoldingNotes")
1497    public ModelAndView addEOWHoldingNotes(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1498                                           HttpServletRequest request, HttpServletResponse response) {
1499        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1500        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1501        String selectedPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1502        int selectedExtentIndex = Integer.parseInt(StringUtils.substring(selectedPath,
1503                (StringUtils.indexOf(selectedPath, "[") + 1),
1504                StringUtils.lastIndexOf(selectedPath, "]")));
1505        index++;
1506        List<Note> holdingsNote = instanceEditorForm.getSelectedHolding().getExtentOfOwnership()
1507                .get(selectedExtentIndex).getNote();
1508        holdingsNote.add(index, new Note());
1509        //        return super.updateComponent(instanceEditorForm, result, request, response);
1510        return null;
1511    }
1512
1513    @RequestMapping(params = "methodToCall=removeEOWHoldingNotes")
1514    public ModelAndView removeEOWHoldingNotes(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
1515                                              HttpServletRequest request, HttpServletResponse response) {
1516        InstanceEditorForm instanceEditorForm = (InstanceEditorForm) form;
1517        int index = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1518        String selectedPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1519        int selectedExtentIndex = Integer.parseInt(StringUtils.substring(selectedPath,
1520                (StringUtils.indexOf(selectedPath, "[") + 1),
1521                StringUtils.lastIndexOf(selectedPath, "]")));
1522        List<Note> holdingsNote = instanceEditorForm.getSelectedHolding().getExtentOfOwnership()
1523                .get(selectedExtentIndex).getNote();
1524        if (holdingsNote.size() > 1) {
1525            holdingsNote.remove(index);
1526        }
1527        //        return super.updateComponent(instanceEditorForm, result, request, response);
1528        return null;
1529    }
1530
1531    @Override
1532    public EditorForm addORDeleteFields(EditorForm editorForm, HttpServletRequest request) {
1533        return null;
1534    }
1535
1536    @Override
1537    public EditorForm deleteVerify(EditorForm editorForm) throws Exception {
1538        LOG.info("in instance editor class");
1539        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
1540        String docId = editorForm.getDocId();
1541        String operation = "deleteVerify";
1542        //        String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1543        //        LOG.info("deleteVerify responseXml-->" + responseXml);
1544        //        editorForm.setDeleteVerifyResponse(responseXml);
1545        editorForm.setShowDeleteTree(true);
1546        editorForm.setHasLink(true);
1547        //        Node<DocumentTreeNode, String> docTree = buildDocSelectionTree(responseXml);
1548        List<String> uuidList = new ArrayList<>(0);
1549        uuidList.add(editorForm.getDocId());
1550        DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1551        Node<DocumentTreeNode, String> docTree = documentSelectionTree.add(uuidList, editorForm.getDocType());
1552        editorForm.getDocTree().setRootElement(docTree);
1553        workInstanceOlemlForm.setViewId("DeleteViewPage");
1554
1555
1556        return workInstanceOlemlForm;
1557    }
1558
1559    private Node<DocumentTreeNode, String> buildDocSelectionTree(String responseXml) throws SolrServerException {
1560        Response response = new ResponseHandler().toObject(responseXml);
1561        List<ResponseDocument> responseDocumentList = response.getDocuments();
1562        List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>();
1563        List<WorkBibDocument> bibDocumentList = new ArrayList<WorkBibDocument>();
1564        List<WorkInstanceDocument> instanceDocumentList = new ArrayList<WorkInstanceDocument>();
1565        WorkHoldingsDocument workHoldingsDocument = null;
1566        WorkInstanceDocument workInstanceDocument = null;
1567        WorkBibDocument workBibDocument = null;
1568        WorkItemDocument workItemDocument = null;
1569        List<String> uuidList = new ArrayList<String>();
1570        String docType = null;
1571
1572        for (ResponseDocument responseDocument : responseDocumentList) {
1573
1574            if (responseDocument.getType().equalsIgnoreCase(DocType.ITEM.getCode())) {
1575                workItemDocument = new WorkItemDocument();
1576                workItemDocument.setItemIdentifier(responseDocument.getUuid());
1577                uuidList.add(responseDocument.getUuid());
1578
1579                docType = responseDocument.getType();
1580                workItemDocumentList.add(workItemDocument);
1581
1582            } else if (responseDocument.getType().equalsIgnoreCase(DocType.HOLDINGS.getCode())) {
1583                workHoldingsDocument = new WorkHoldingsDocument();
1584                docType = responseDocument.getType();
1585                workHoldingsDocument.setHoldingsIdentifier(responseDocument.getUuid());
1586                uuidList.add(responseDocument.getUuid());
1587            } else if (responseDocument.getType().equalsIgnoreCase(DocType.BIB.getDescription())) {
1588                workBibDocument = new WorkBibDocument();
1589                uuidList.add(responseDocument.getUuid());
1590                workBibDocument.setId(responseDocument.getUuid());
1591                docType = responseDocument.getType();
1592                bibDocumentList.add(workBibDocument);
1593
1594
1595            } else if (responseDocument.getType().equalsIgnoreCase(DocType.INSTANCE.getCode())) {
1596                workInstanceDocument = new WorkInstanceDocument();
1597                workInstanceDocument.setInstanceIdentifier(responseDocument.getUuid());
1598                uuidList.add(responseDocument.getUuid());
1599                docType = responseDocument.getType();
1600                instanceDocumentList.add(workInstanceDocument);
1601            }
1602        }
1603        if (workItemDocumentList.size() > 0) {
1604            if (workInstanceDocument != null) {
1605                workInstanceDocument.setHoldingsDocument(workHoldingsDocument);
1606                workInstanceDocument.setItemDocumentList(workItemDocumentList);
1607            }
1608        }
1609        if (instanceDocumentList.size() > 0) {
1610            if (workBibDocument != null) {
1611                workBibDocument.setWorkInstanceDocumentList(instanceDocumentList);
1612            }
1613        }
1614
1615        DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1616
1617        Node<DocumentTreeNode, String> rootNode = documentSelectionTree.add(uuidList, docType);
1618
1619
1620/*
1621        if(workItemDocumentList != null)
1622        {
1623            if(instanceDocumentList != null)
1624            {
1625                if(bibDocumentList  != null)
1626                {
1627
1628                    documentSelectionTree.buildNodeList(bibDocumentList);
1629
1630                }
1631                else
1632                {
1633                    documentSelectionTree.buildInstanceNode(workInstanceDocument);
1634                }
1635
1636            }
1637            else
1638            {
1639                documentSelectionTree.buildItemNode(workItemDocument);
1640            }
1641
1642        }
1643*/
1644
1645
1646        return rootNode;
1647    }
1648
1649    @Override
1650    public EditorForm delete(EditorForm editorForm) throws Exception {
1651        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
1652        WorkBibMarcForm workBibMarcForm = new WorkBibMarcForm();
1653        BusinessObjectService boService = KRADServiceLocator.getBusinessObjectService();
1654        boolean itemCheck = false;
1655        //    Response response = new ResponseHandler().toObject(editorForm.getDeleteVerifyResponse());
1656
1657//        List<ResponseDocument> responseDocumentList = response.getDocuments();
1658        String docId = editorForm.getDocId();
1659//        for (ResponseDocument responseDocument : responseDocumentList) {
1660//            docId = responseDocument.getUuid();
1661//            editorForm.setDocCategory(responseDocument.getCategory());
1662//            editorForm.setDocType(responseDocument.getType());
1663//            editorForm.setDocFormat(responseDocument.getFormat());
1664//        }
1665        LOG.info("docId-->" + docId);
1666        String operation = "delete";
1667        List<String> itemIdList = new ArrayList<String>();
1668        if (editorForm.getDocType().equalsIgnoreCase("item") && docId != null) {
1669            itemIdList.add(docId);
1670        } else if (docId != null) {
1671            itemIdList = getDocstoreHelperService().getItemIdsInInstance(docId);
1672        }
1673        for (String itemUuid : itemIdList) {
1674            Map<String, String> map = new HashMap<>();
1675            Map<String, String> uuidMap = new HashMap<>();
1676            map.put("itemUUID", itemUuid);
1677            uuidMap.put("itemUuid", itemUuid);
1678            List<OleCopy> listOfValues = (List<OleCopy>) boService.findMatching(OleCopy.class, map);
1679            if (listOfValues.size() != 0) {
1680                itemCheck = true;
1681                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_PURCHASE_ORDER_FAIL_MESSAGE, "Item");
1682                break;
1683            } else {
1684                List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) boService.findMatching(OleLoanDocument.class, uuidMap);
1685                if (oleLoanDocuments.size() != 0) {
1686                    itemCheck = true;
1687                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_LOANED_FAIL_MESSAGE);
1688                    break;
1689                } else {
1690                    List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) boService.findMatching(OleDeliverRequestBo.class, uuidMap);
1691                    if (oleDeliverRequestBos.size() != 0) {
1692                        itemCheck = true;
1693                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.DELETE_REQUEST_FAIL_MESSAGE);
1694                        break;
1695                    }
1696                }
1697            }
1698        }
1699        if (!itemCheck) {
1700            String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1701            updateTreeData(editorForm);
1702            Response response = new ResponseHandler().toObject(responseXml);
1703            for (ResponseDocument responseDocument : response.getDocuments()) {
1704                if (responseDocument.getStatus().contains("failure")) {
1705                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "docstore.response", responseDocument.getStatusMessage());
1706                } else if (responseDocument.getStatus().contains("success")) {
1707                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.delete.message");
1708                } else {
1709                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.delete.fail.message");
1710                }
1711            }
1712            /*if (responseXml.contains("Success") && !responseXml.contains("failure")) {
1713                GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "record.delete.message");
1714            } else {
1715                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.delete.fail.message");
1716            }*/
1717        }
1718        editorForm.setShowDeleteTree(false);
1719        editorForm.setHasLink(false);
1720        workBibMarcForm.setViewId("DeleteViewPage");
1721        return workBibMarcForm;
1722    }
1723
1724    @Override
1725    public EditorForm addORRemoveExtentOfOwnership(EditorForm editorForm, HttpServletRequest request) {
1726        String methodName = request.getParameter("methodToCall");
1727        if (methodName.equalsIgnoreCase("addExtentOfOwnership")) {
1728            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1729            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1730            index++;
1731            List<ExtentOfOwnership> extentOfOwnershipForUI = workInstanceOlemlForm.getSelectedHolding().getExtentOfOwnership();
1732            ExtentOfOwnership extentOfOwnership = new ExtentOfOwnership();
1733            extentOfOwnership.getNote().add(new Note());
1734            extentOfOwnershipForUI.add(index, extentOfOwnership);
1735            editorForm.setDocumentForm(workInstanceOlemlForm);
1736        } else if (methodName.equalsIgnoreCase("removeExtentOfOwnership")) {
1737            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1738            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1739            List<ExtentOfOwnership> extentOfOwnershipForUI = workInstanceOlemlForm.getSelectedHolding().getExtentOfOwnership();
1740            if (extentOfOwnershipForUI.size() > 1) {
1741                extentOfOwnershipForUI.remove(index);
1742            }
1743            editorForm.setDocumentForm(workInstanceOlemlForm);
1744        } else if (methodName.equalsIgnoreCase("addEOWHoldingNotes")) {
1745            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1746            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1747            String selectedPath = editorForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1748            int selectedExtentIndex = Integer.parseInt(StringUtils.substring(selectedPath,
1749                    (StringUtils.indexOf(selectedPath, "[") + 1),
1750                    StringUtils.lastIndexOf(selectedPath, "]")));
1751            index++;
1752            List<Note> holdingsNote = workInstanceOlemlForm.getSelectedHolding().getExtentOfOwnership()
1753                    .get(selectedExtentIndex).getNote();
1754            holdingsNote.add(index, new Note());
1755            editorForm.setDocumentForm(workInstanceOlemlForm);
1756        } else if (methodName.equalsIgnoreCase("removeEOWHoldingNotes")) {
1757            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1758            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1759            String selectedPath = editorForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
1760            int selectedExtentIndex = Integer.parseInt(StringUtils.substring(selectedPath,
1761                    (StringUtils.indexOf(selectedPath, "[") + 1),
1762                    StringUtils.lastIndexOf(selectedPath, "]")));
1763            List<Note> holdingsNote = workInstanceOlemlForm.getSelectedHolding().getExtentOfOwnership()
1764                    .get(selectedExtentIndex).getNote();
1765            if (holdingsNote.size() > 1) {
1766                holdingsNote.remove(index);
1767            }
1768            editorForm.setDocumentForm(workInstanceOlemlForm);
1769        }
1770        return editorForm;
1771    }
1772
1773    @Override
1774    public EditorForm addORRemoveAccessInformationAndHoldingsNotes(EditorForm editorForm, HttpServletRequest request) {
1775        String methodName = request.getParameter("methodToCall");
1776        if (methodName.equalsIgnoreCase("addAccessInformation")) {
1777            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1778            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1779            index++;
1780            List<Uri> accessInformation = workInstanceOlemlForm.getSelectedHolding().getUri();
1781            accessInformation.add(index, new Uri());
1782            editorForm.setDocumentForm(workInstanceOlemlForm);
1783        } else if (methodName.equalsIgnoreCase("removeAccessInformation")) {
1784            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1785            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1786            List<Uri> accessInformation = workInstanceOlemlForm.getSelectedHolding().getUri();
1787            if (accessInformation.size() > 1) {
1788                accessInformation.remove(index);
1789            }
1790            editorForm.setDocumentForm(workInstanceOlemlForm);
1791        } else if (methodName.equalsIgnoreCase("addHoldingNotes")) {
1792            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1793            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1794            index++;
1795            List<Note> holdingsNote = workInstanceOlemlForm.getSelectedHolding().getNote();
1796            holdingsNote.add(index, new Note());
1797            editorForm.setDocumentForm(workInstanceOlemlForm);
1798        } else if (methodName.equalsIgnoreCase("removeHoldingNotes")) {
1799            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1800            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1801            List<Note> holdingsNote = workInstanceOlemlForm.getSelectedHolding().getNote();
1802            if (holdingsNote.size() > 1) {
1803                holdingsNote.remove(index);
1804            }
1805            editorForm.setDocumentForm(workInstanceOlemlForm);
1806        }
1807        return editorForm;
1808    }
1809
1810    /**
1811     * Validates the Holdings data and returns true if it is valid
1812     *
1813     * @param workInstanceOlemlForm
1814     * @return
1815     */
1816    private boolean isValidHoldingsData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1817        OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
1818        String location = null;
1819        if (oleHoldings != null && oleHoldings.getLocation() != null && oleHoldings.getLocation().getLocationLevel() != null) {
1820            location = oleHoldings.getLocation().getLocationLevel().getName();
1821        }
1822        if (location != null && location.length() != 0 && !isValidLocation(location)) {
1823            //workInstanceOlemlForm.setMessage("<font size='3' color='red'>Please enter valid location.</font>");
1824            GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1825            workInstanceOlemlForm.setValidInput(false);
1826            return false;
1827        }
1828        return true;
1829    }
1830
1831    /**
1832     * Validates the item data and returns true if it is valid
1833     *
1834     * @param workInstanceOlemlForm
1835     * @return
1836     */
1837    private boolean isValidItemData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1838        Item item = workInstanceOlemlForm.getSelectedItem();
1839        boolean isValidItem = true;
1840        StringBuffer stringBuffer = new StringBuffer();
1841        String oldItemStatus = workInstanceOlemlForm.getOldItemStatus();
1842        String itemStatus = item.getItemStatus().getCodeValue();
1843        String itemProperty = getInstanceEditorFormDataHandler()
1844                .getParameter(OLEConstants.DESC_NMSPC, OLEConstants.DESCRIBE_COMPONENT, OLEParameterConstants.ITEM_STATUS_READONLY);
1845        String[] itemArray = itemProperty.split(",");
1846        //If current item status is changed when compared with previous status
1847        if ((StringUtils.isNotEmpty(itemStatus)) && (!itemStatus.equals(oldItemStatus))) {
1848            for (String status : itemArray) {
1849                if (status.equalsIgnoreCase(itemStatus)) {
1850                    stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_INVALID + "</font>");
1851                    //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1852                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "invalid.item.status");
1853                    return false;
1854                }
1855            }
1856        }
1857        String location = "";
1858        String holdingsLocation = "";
1859        if (item.getLocation() != null) {
1860            location = item.getLocation().getLocationLevel().getName();
1861        }
1862        OleHoldings holdings = workInstanceOlemlForm.getSelectedHolding();
1863        if (holdings.getLocation() != null) {
1864            holdingsLocation = holdings.getLocation().getLocationLevel().getName();
1865        }
1866
1867
1868        //Display error message when item status is empty
1869        if (!(item.getItemStatus() != null && item.getItemStatus().getCodeValue().length() > 0)) {
1870            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_ERRORMESSAGE + "</font>");
1871            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.status.required");
1872            workInstanceOlemlForm.setValidInput(false);
1873            isValidItem = false;
1874        }
1875
1876        //Display error message when item type is empty
1877        if (!(item.getItemType() != null && item.getItemType().getCodeValue().length() > 0)) {
1878            stringBuffer.append("<br>");
1879            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERRORMESSAGE + "</font>");
1880            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.type.required");
1881            workInstanceOlemlForm.setValidInput(false);
1882            isValidItem = false;
1883        }
1884
1885        if (holdingsLocation != null && holdingsLocation.length() != 0 && !isValidLocation(holdingsLocation)) {
1886            stringBuffer.append("<br>");
1887            GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1888            workInstanceOlemlForm.setValidInput(false);
1889            isValidItem = false;
1890        }
1891        //Display error message when location is invalid
1892        if (location != null && location.length() != 0 && !isValidLocation(location)) {
1893            stringBuffer.append("<br>");
1894            //stringBuffer.append("<font size='3' color='red'>Please enter the valid location.</font>");
1895            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.location.locationLevel.name", "error.location");
1896            workInstanceOlemlForm.setValidInput(false);
1897            isValidItem = false;
1898        }
1899
1900        boolean hasPermission = canUpdateItemStatus(GlobalVariables.getUserSession().getPrincipalId());
1901        if (hasPermission) {
1902            if (StringUtils.isEmpty(stringBuffer.toString())) {
1903                isValidItem = true;
1904            } else {
1905                isValidItem = false;
1906            }
1907        } else {
1908            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERROR_MESSAGE + "</font>");
1909            //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1910            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.type.authorization");
1911            return false;
1912        }
1913        return isValidItem;
1914    }
1915
1916    private boolean isValidLocation(String location) {
1917
1918        List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
1919        if (locationList != null && locationList.size() > 0) {
1920            for (String locationValue : locationList) {
1921                if (locationValue.equalsIgnoreCase(location)) {
1922                    return true;
1923                }
1924            }
1925        }
1926        return false;
1927    }
1928
1929    @Override
1930    public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1931        String methodName = request.getParameter("methodToCall");
1932        if (methodName.equalsIgnoreCase("addItemNote")) {
1933            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1934            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1935            index++;
1936            List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1937            itemNote.add(index, new Note());
1938            editorForm.setDocumentForm(workInstanceOlemlForm);
1939        } else if (methodName.equalsIgnoreCase("removeItemNote")) {
1940            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1941            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1942            List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1943            if (itemNote.size() > 1) {
1944                itemNote.remove(index);
1945            }
1946            editorForm.setDocumentForm(workInstanceOlemlForm);
1947        }
1948        return editorForm;
1949    }
1950
1951    private List<Uri> ensureAtleastOneUri(List<Uri> uris) {
1952        if (uris == null) {
1953            uris = new ArrayList<Uri>();
1954        }
1955        if (uris.size() == 0) {
1956            Uri uri = new Uri();
1957            uris.add(uri);
1958        }
1959        return uris;
1960    }
1961
1962    private List<Note> ensureAtleastOneNote(List<Note> notes) {
1963        if (notes == null) {
1964            notes = new ArrayList<Note>();
1965        }
1966        if (notes.size() == 0) {
1967            Note note = new Note();
1968            notes.add(note);
1969        }
1970        return notes;
1971    }
1972
1973    private List<ExtentOfOwnership> ensureAtleastOneExtentOfOwnership(List<ExtentOfOwnership> extentOfOwnerships) {
1974        if (extentOfOwnerships == null) {
1975            extentOfOwnerships = new ArrayList<ExtentOfOwnership>();
1976        }
1977        if (extentOfOwnerships.size() == 0) {
1978            ExtentOfOwnership extentOfOwnership = new ExtentOfOwnership();
1979            extentOfOwnership.getNote().add(new Note());
1980            extentOfOwnerships.add(0, extentOfOwnership);
1981        }
1982        return extentOfOwnerships;
1983    }
1984
1985
1986    /**
1987     * Shows the linked Bibs corresponging to Holdings/Item
1988     *
1989     * @param editorForm
1990     * @return
1991     */
1992    @Override
1993    public EditorForm showBibs(EditorForm editorForm) {
1994        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
1995        QueryService queryService = QueryServiceImpl.getInstance();
1996        List<String> bibUUIDList = new ArrayList<String>();
1997        String instanceId = "";
1998        String docType = editorForm.getDocType();
1999        List<WorkBibDocument> workBibDocumentList = new ArrayList<WorkBibDocument>();
2000        try {
2001
2002            if ((docType.equalsIgnoreCase(DocType.INSTANCE.getCode()) || docType
2003                    .equalsIgnoreCase(DocType.HOLDINGS.getCode())) || (docType
2004                    .equalsIgnoreCase(DocType.ITEM.getCode()))) {
2005                instanceId = editorForm.getInstanceId();
2006            }
2007            if (StringUtils.isNotEmpty(instanceId)) {
2008                bibUUIDList = queryService.queryForBibs(instanceId);
2009            }
2010            DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
2011            if (bibUUIDList != null && bibUUIDList.size() > 0) {
2012                for (String bibUUID : bibUUIDList) {
2013                    WorkBibDocument workBibDocument = new WorkBibDocument();
2014                    workBibDocument.setId(bibUUID);
2015                    workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument);
2016                    workBibDocumentList.add(workBibDocument);
2017                }
2018            }
2019
2020            editorForm.setWorkBibDocumentList(workBibDocumentList);
2021        } catch (SolrServerException e) {
2022            LOG.error("Exception:" + e.getMessage(), e);
2023        }
2024        workInstanceOlemlForm.setViewId("ShowBibViewPage");
2025        return workInstanceOlemlForm;
2026    }
2027
2028    private boolean canUpdateItemStatus(String principalId) {
2029        LOG.debug("Inside the canUpdateItemStatus method");
2030        PermissionService service = KimApiServiceLocator.getPermissionService();
2031        return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_UPDATE_IEM_STATUS);
2032    }
2033
2034    public EditorForm copy(EditorForm editorForm) {
2035        return null;
2036    }
2037
2038    private XMLGregorianCalendar getGregorianCalendar(Date date) throws DatatypeConfigurationException {
2039        GregorianCalendar gregory = new GregorianCalendar();
2040        gregory.setTime(date);
2041        XMLGregorianCalendar dealCloseDate = DatatypeFactory.newInstance()
2042                .newXMLGregorianCalendar(gregory);
2043        return dealCloseDate;
2044    }
2045}