View Javadoc
1   package org.kuali.ole.select.document.service.impl;
2   
3   import org.apache.commons.httpclient.HttpClient;
4   import org.apache.commons.httpclient.NameValuePair;
5   import org.apache.commons.httpclient.methods.DeleteMethod;
6   import org.apache.commons.lang3.StringUtils;
7   import org.apache.cxf.helpers.IOUtils;
8   import org.kuali.ole.describe.bo.OleLocation;
9   import org.kuali.ole.describe.bo.OleLocationLevel;
10  import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
11  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
12  import org.kuali.ole.docstore.common.document.*;
13  import org.kuali.ole.docstore.common.document.HoldingsTree;
14  import org.kuali.ole.docstore.common.document.content.enums.DocCategory;
15  import org.kuali.ole.docstore.common.document.content.instance.*;
16  import org.kuali.ole.docstore.common.document.content.instance.Item;
17  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
18  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
19  import org.kuali.ole.docstore.model.enums.DocType;
20  import org.kuali.ole.docstore.model.xmlpojo.ingest.*;
21  import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.InstanceCollection;
22  import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler;
23  import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler;
24  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
25  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkInstanceOlemlRecordProcessor;
26  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
27  import org.kuali.ole.module.purap.PurapConstants;
28  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
29  import org.kuali.ole.module.purap.businessobject.PurApItem;
30  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
31  import org.kuali.ole.select.bo.OLEDonor;
32  import org.kuali.ole.select.bo.OLELinkPurapDonor;
33  import org.kuali.ole.select.bo.OleVendorAccountInfo;
34  import org.kuali.ole.select.businessobject.OleCopies;
35  import org.kuali.ole.select.businessobject.OleCopy;
36  import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
37  import org.kuali.ole.select.document.OleRequisitionDocument;
38  import org.kuali.ole.select.document.service.OleCopyHelperService;
39  import org.kuali.ole.select.document.service.OleDocstoreHelperService;
40  import org.kuali.ole.select.service.WebClientService;
41  import org.kuali.ole.sys.OLEConstants;
42  import org.kuali.ole.sys.context.SpringContext;
43  import org.kuali.ole.util.DocstoreUtil;
44  import org.kuali.rice.core.api.config.property.ConfigContext;
45  import org.kuali.rice.core.api.config.property.ConfigurationService;
46  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
47  import org.kuali.rice.krad.service.KRADServiceLocator;
48  import org.kuali.rice.krad.util.GlobalVariables;
49  
50  import java.io.*;
51  import java.net.URL;
52  import java.net.URLConnection;
53  import java.net.URLEncoder;
54  import java.util.*;
55  
56  
57  /**
58   * This class...
59   */
60  public class OleDocstoreHelperServiceImpl implements OleDocstoreHelperService {
61  
62      private ConfigurationService kualiConfigurationService;
63      private WebClientService webClientService;
64  
65      private final String UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkIn&stringContent=";
66      private final String CHECKOUT_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkOut&uuid=";
67      private final String CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING = "docAction=ingestContent&stringContent=";
68      private WorkItemOlemlRecordProcessor workItemOlemlRecordProcessor;
69      private WorkHoldingOlemlRecordProcessor workHoldingOlemlRecordProcessor;
70      private WorkInstanceOlemlRecordProcessor workInstanceOlemlRecordProcessor;
71      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger
72              .getLogger(OleDocstoreHelperServiceImpl.class);
73      private static final String DOCSTORE_URL = "docstore.url";
74      private DocstoreClientLocator docstoreClientLocator;
75      int copyCount = 0;
76      boolean copyFlag = false;
77      boolean newCopyFlag = false;
78      private HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
79      private DocstoreUtil docstoreUtil=new DocstoreUtil();
80  
81      public DocstoreClientLocator getDocstoreClientLocator() {
82          if (docstoreClientLocator == null) {
83              docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
84          }
85          return docstoreClientLocator;
86      }
87  
88      @Override
89      public String rollbackData(String bibiUUID) {
90          RequestHandler requestHandler = new RequestHandler();
91          Request request = new Request();
92          request.setUser("mock_user");
93          request.setOperation("deleteWithLinkedDocs");
94          RequestDocument requestDocument = new RequestDocument();
95          requestDocument.setId(bibiUUID);
96          requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
97          requestDocument.setType(OLEConstants.BIB_TYPE_BIBLIOGRAPHY);
98          requestDocument.setFormat(OLEConstants.BIB_FORMAT_MARC);
99          Content content = new Content();
100         content.setContent("");
101         requestDocument.setContent(content);
102         requestDocument.setLinkedRequestDocuments(Collections.<RequestDocument>emptyList());
103         request.setRequestDocuments(Arrays.asList(requestDocument));
104         String rollBackXml = requestHandler.toXML(request);
105         return rollbackDataFromXml(rollBackXml);
106     }
107 
108 
109     private String rollbackDataFromXml(String xmlForRollback) {
110 
111         String response = "";
112         String queryString = kualiConfigurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_POST_DATA_DELETE_KEY) + URLEncoder.encode(xmlForRollback);
113         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
114         String contentType = kualiConfigurationService.getPropertyValueAsString(OLEConstants.DOCSTORE_APP_CONTENT_TYPE_KEY);
115         try {
116             response = webClientService.sendRequest(docstoreURL, contentType, queryString + queryString);
117         } catch (Exception ex) {
118             ex.printStackTrace();
119         }
120         return response;
121     }
122 
123 
124     public ConfigurationService getConfigurationService() {
125         return kualiConfigurationService;
126     }
127 
128 
129     public void setConfigurationService(ConfigurationService kualiConfigurationService) {
130         this.kualiConfigurationService = kualiConfigurationService;
131     }
132 
133 
134     public WebClientService getWebClientService() {
135         return webClientService;
136     }
137 
138 
139     public void setWebClientService(WebClientService webClientService) {
140         this.webClientService = webClientService;
141     }
142 
143     public void performDocstoreUpdateForRequisitionAndPOItem(PurchaseOrderDocument purchaseOrderDocument, OlePurchaseOrderItem singleItem, BibTree bibTree, String documentTypeName, String note) throws Exception {
144         List<OleCopies> copies = singleItem.getCopies();
145         List<OleCopy> copyList = singleItem.getCopyList();
146         List<OLELinkPurapDonor> oleDonors = singleItem.getOleDonors();
147         String itemTypeDescription = singleItem.getItemTypeDescription();
148         String itemTitleId = singleItem.getItemTitleId();
149         String poLineItemId = singleItem.getItemIdentifier() != null ? singleItem.getItemIdentifier().toString() : null;
150         String poNumber = purchaseOrderDocument.getPurapDocumentIdentifier() != null ? purchaseOrderDocument.getPurapDocumentIdentifier().toString() : null;
151         String reqsInitiatorName = getREQSInitiatorName(purchaseOrderDocument);
152         if (singleItem.getLinkToOrderOption() != null) {
153             if (singleItem.getLinkToOrderOption().equals(OLEConstants.EB_PRINT) || singleItem.getLinkToOrderOption().equals(OLEConstants.EB_ELECTRONIC)) {
154                 performDocstoreCRUDOperationForExistingBib(poNumber, singleItem.getLinkToOrderOption(), bibTree, copyList, oleDonors, poLineItemId, itemTypeDescription, singleItem.getItemStatus(), itemTitleId, singleItem, documentTypeName, note, reqsInitiatorName);
155             } else if (singleItem.getLinkToOrderOption().equals(OLEConstants.NB_ELECTRONIC) && copyList != null && copyList.size() > 0) {
156                 if (documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT) ||
157                         documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT) ||
158                         documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT) ||
159                         documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT) ||
160                         documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT) ||
161                         documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)){
162                      updateEInstance(copyList.get(0), oleDonors);
163                 }   else {
164                     createEInstance(copyList.get(0), oleDonors, bibTree,reqsInitiatorName);
165                 }
166             } else if (singleItem.getLinkToOrderOption().equals(OLEConstants.NB_PRINT)) {
167                 performDocstoreCRUDOperationForItemNew(poNumber, copies, copyList, oleDonors, itemTypeDescription, itemTitleId, bibTree, poLineItemId, singleItem.getItemStatus(), singleItem.getItemLocation(), documentTypeName, note, singleItem, reqsInitiatorName);
168             } else if (singleItem.getLinkToOrderOption().equals(org.kuali.ole.OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT) || singleItem.getLinkToOrderOption().equals(org.kuali.ole.OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI)) {
169                 performDocstoreCRUDOperationFoROrderRecordImportMarcOnlyPrint(poNumber, copyList, singleItem, oleDonors, bibTree, poLineItemId, reqsInitiatorName);
170             } else if (singleItem.getLinkToOrderOption().equals(org.kuali.ole.OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_ELECTRONIC) || singleItem.getLinkToOrderOption().equals(org.kuali.ole.OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_ELECTRONIC)) {
171                 performDocstoreCRUDOperationFoROrderRecordImportMarcOnlyElectronic(copyList, oleDonors, bibTree, reqsInitiatorName);
172             }
173         }
174     }
175 
176     private String getREQSInitiatorName(PurchaseOrderDocument purchaseOrderDocument) {
177         String reqInitiatorId = "";
178         String reqInitiatorName = "";
179         OleRequisitionDocument oleRequisitionDocument = (OleRequisitionDocument) KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleRequisitionDocument.class,purchaseOrderDocument.getRequisitionIdentifier());
180         if(oleRequisitionDocument != null && oleRequisitionDocument.getDocumentHeader() != null && oleRequisitionDocument.getDocumentHeader().getWorkflowDocument() != null){
181             reqInitiatorId = oleRequisitionDocument.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
182             if(reqInitiatorId != null && !reqInitiatorId.equalsIgnoreCase("")){
183                 if(KimApiServiceLocator.getPersonService() != null && KimApiServiceLocator.getPersonService().getPerson(reqInitiatorId) != null){
184                     reqInitiatorName = KimApiServiceLocator.getPersonService().getPerson(reqInitiatorId).getPrincipalName();
185                 }
186             }
187         }
188         return reqInitiatorName;
189     }
190 
191     private void performDocstoreCRUDOperationFoROrderRecordImportMarcOnlyPrint(String poNumber, List<OleCopy> oleCopyList, OlePurchaseOrderItem singleItem,
192                                                                                List<OLELinkPurapDonor> oleDonors, BibTree bibTree, String poLineItemId, String initiatorName) throws Exception {
193         if (oleCopyList != null) {
194             boolean holdingsExists = false;
195             for (OleCopy oleCopy : oleCopyList) {
196                 if (oleCopy != null && oleCopy.getInstanceId() != null) {
197                     holdingsExists = true;
198                     Holdings holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleCopy.getInstanceId());
199                     org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
200                     oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
201                     oleHoldings.setLocation(setHoldingDetails(oleCopy).getLocation());
202                     holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
203                     getDocstoreClientLocator().getDocstoreClient().updateHoldings(holdings);
204                     if (oleCopy.getItemUUID() != null) {
205                         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleCopy.getItemUUID());
206                         Item itemContent = new ItemOlemlRecordProcessor().fromXML(item.getContent());
207                         List<DonorInfo> donorInfoList = setDonorInfoToItem(singleItem.getOleDonors(), new ArrayList<DonorInfo>());
208                         itemContent.setDonorInfo(donorInfoList);
209                         setItemDetails(itemContent, oleCopy, singleItem, oleDonors, poNumber);
210                         item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
211                         item.setId(itemContent.getItemIdentifier());
212                         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
213                     } else {
214                         Item item = new Item();
215                         setItemDetails(item, oleCopy, singleItem, oleDonors, poNumber);
216                         org.kuali.ole.docstore.common.document.Item itemDocument = new org.kuali.ole.docstore.common.document.Item();
217                         itemDocument.setContent(new ItemOlemlRecordProcessor().toXML(item));
218                         itemDocument.setCreatedBy(initiatorName);
219                         itemDocument.setCategory(OLEConstants.ITEM_CATEGORY);
220                         itemDocument.setType(OLEConstants.ITEM_TYPE);
221                         itemDocument.setFormat(OLEConstants.ITEM_FORMAT);
222                         if (StringUtils.isNotBlank(oleCopy.getInstanceId())) {
223                             itemDocument.setHolding(holdings);
224                             getDocstoreClientLocator().getDocstoreClient().createItem(itemDocument);
225                         }
226                         oleCopy.setItemUUID(itemDocument.getId());
227                     }
228                 }
229             }
230             if (!holdingsExists) {
231                 OleCopyHelperService oleCopyHelperService = new OleCopyHelperServiceImpl();
232                 HashMap<String, List<OleCopy>> copyListBasedOnLocation = oleCopyHelperService.getCopyListBasedOnLocation(oleCopyList, singleItem.getItemTitleId());
233                 Iterator<Map.Entry<String, List<OleCopy>>> entries = copyListBasedOnLocation.entrySet().iterator();
234                 while (entries.hasNext()) {
235                     Map.Entry<String, List<OleCopy>> entry = entries.next();
236                     List<OleCopy> copyList = entry.getValue();
237                     createOleHoldingsTree(poNumber, bibTree, copyList, poLineItemId, oleDonors, oleCopyList, singleItem.getItemTypeDescription(), singleItem.getItemStatus(), singleItem, initiatorName);
238                 }
239             }
240         }
241     }
242 
243     private void performDocstoreCRUDOperationFoROrderRecordImportMarcOnlyElectronic(List<OleCopy> oleCopyList,List<OLELinkPurapDonor> oleDonors, BibTree bibTree, String initiatorName) throws Exception {
244         if (oleCopyList != null && oleCopyList.size() > 0) {
245             OleCopy oleCopy = oleCopyList.get(0);
246             if (oleCopy != null) {
247                 if (oleCopy.getInstanceId() != null) {
248                     updateEInstance(oleCopy,oleDonors);
249                 } else {
250                     createEInstance(oleCopy, oleDonors, bibTree, initiatorName);
251                 }
252             }
253         }
254     }
255 
256     public void setItemDetails(Item itemContent, OleCopy oleCopy, OlePurchaseOrderItem singleItem, List<OLELinkPurapDonor> oleDonors, String poNumber) {
257         if (StringUtils.isBlank(itemContent.getEnumeration())) {
258             itemContent.setEnumeration(oleCopy.getEnumeration());
259         }
260         if (itemContent.getItemStatus() == null ||
261                 (itemContent.getItemStatus() != null && itemContent.getItemStatus().getCodeValue() == null && itemContent.getItemStatus().getFullValue() == null)) {
262             ItemStatus itemStatus = new ItemStatus();
263             itemStatus.setCodeValue(singleItem.getItemStatus());
264             itemStatus.setFullValue(singleItem.getItemStatus());
265             itemContent.setItemStatus(itemStatus);
266         }
267         itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
268         if (singleItem != null) {
269             itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
270             if (singleItem.getExtendedPrice() != null) {
271                 itemContent.setPrice(singleItem.getExtendedPrice().toString());
272             }
273             itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
274         }
275         List<OLELinkPurapDonor> oleReqDonors = new ArrayList<>();
276         List<DonorInfo> donorInfoList = new ArrayList<>();
277         boolean flag = true;
278         for (OLELinkPurapDonor reqDonorInfo : oleDonors) {
279             if (itemContent.getDonorInfo() != null && itemContent.getDonorInfo().size() > 0) {
280                 for (DonorInfo itemDonorInfo : itemContent.getDonorInfo()) {
281                     if (itemDonorInfo.getDonorCode().equals(itemDonorInfo.getDonorCode())) {
282                         flag = false;
283                         break;
284                     }
285                 }
286                 if (flag) {
287                     oleReqDonors.add(reqDonorInfo);
288                 }
289             }
290         }
291         if (itemContent.getDonorInfo() != null && itemContent.getDonorInfo().size() > 0) {
292             donorInfoList = setDonorInfoToItem(oleReqDonors, itemContent.getDonorInfo());
293         } else {
294             donorInfoList = setDonorInfoToItem(oleDonors, itemContent.getDonorInfo());
295         }
296         itemContent.setDonorInfo(donorInfoList);
297     }
298 
299     private void performDocstoreCRUDOperationForExistingBib(String poNumber, String linkToOrderOption, BibTree bibTree, List<OleCopy> oleCopyList, List<OLELinkPurapDonor> oleDonors, String poLineItemId, String itemTypeDescription, String itemStatusValue, String itemTitleId, OlePurchaseOrderItem singleItem, String documentTypeName, String note, String initiatorName) throws Exception {
300         if (linkToOrderOption.equals(OLEConstants.EB_PRINT)) {
301             OleCopyHelperService oleCopyHelperService = new OleCopyHelperServiceImpl();
302             HashMap<String, List<OleCopy>> copyListBasedOnLocation = oleCopyHelperService.getCopyListBasedOnLocation(oleCopyList, itemTitleId);
303             Iterator<Map.Entry<String, List<OleCopy>>> entries = copyListBasedOnLocation.entrySet().iterator();
304             while (entries.hasNext()) {
305                 Map.Entry<String, List<OleCopy>> entry = entries.next();
306                 List<OleCopy> copyList = entry.getValue();
307                 List<OleCopy> newCopyList = new ArrayList<>();
308                 performUpdateForPODocuments(poNumber, bibTree, documentTypeName, poLineItemId, note, singleItem, copyList, oleCopyList, newCopyList, oleDonors, itemTypeDescription, itemStatusValue, initiatorName);
309             }
310         } else if (linkToOrderOption.equals(OLEConstants.EB_ELECTRONIC)) {
311             if (documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT) ||
312                     documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT) ||
313                     documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT) ||
314                     documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT) ||
315                     documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT) ||
316                     documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)){
317                 updateEInstance(oleCopyList.get(0), oleDonors);
318             }   else {
319             createEInstance(oleCopyList.get(0),oleDonors,bibTree, initiatorName);
320         }
321             //createEInstance(oleCopyList.get(0),oleDonors,bibTree);
322         }
323     }
324 
325     private void createEInstance(OleCopy oleCopy, List<OLELinkPurapDonor> oleDonors, BibTree bibTree, String initiatorName)throws Exception{
326         List<DonorInfo> donorInfoList = new ArrayList<>();
327         HoldingsTree holdingsTree = new HoldingsTree();
328         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(oleCopy);
329         oleHoldings.setHoldingsIdentifier(null);
330         donorInfoList = setDonorInfoToItem(oleDonors, oleHoldings.getDonorInfo());
331         oleHoldings.setDonorInfo(donorInfoList);
332         Holdings eHoldings = new EHoldings();
333         eHoldings.setCategory(DocCategory.WORK.getCode());
334         eHoldings.setType(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode());
335         eHoldings.setFormat(org.kuali.ole.docstore.common.document.content.enums.DocFormat.OLEML.getCode());
336         eHoldings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
337         eHoldings.setCreatedBy(initiatorName);
338         Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(bibTree.getBib().getId());
339         eHoldings.setBib(bib);
340         holdingsTree.setHoldings(eHoldings);
341         getDocstoreClientLocator().getDocstoreClient().createHoldingsTree(holdingsTree);
342         oleCopy.setInstanceId(holdingsTree.getHoldings().getId());
343     }
344 
345     private void updateEInstance(OleCopy oleCopy, List<OLELinkPurapDonor> oleDonors) throws Exception{
346         Holdings holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleCopy.getInstanceId());
347         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
348         oleHoldings.setLocation(setHoldingDetails(oleCopy).getLocation());
349         List<OLELinkPurapDonor> oleReqDonors = new ArrayList<>();
350         List<DonorInfo> donorInfoList = new ArrayList<>();
351         boolean flag = true;
352         for (OLELinkPurapDonor reqDonorInfo : oleDonors) {
353             if (oleHoldings.getDonorInfo() != null && oleHoldings.getDonorInfo().size() > 0) {
354                 for (DonorInfo donorInfo : oleHoldings.getDonorInfo()) {
355                     if (donorInfo.getDonorCode().equals(donorInfo.getDonorCode())) {
356                         flag = false;
357                         break;
358                     }
359                 }
360                 if (flag) {
361                     oleReqDonors.add(reqDonorInfo);
362                 }
363             }
364         }
365         if (oleHoldings.getDonorInfo() != null && oleHoldings.getDonorInfo().size() > 0) {
366             donorInfoList = setDonorInfoToItem(oleReqDonors, oleHoldings.getDonorInfo());
367         } else {
368             donorInfoList = setDonorInfoToItem(oleDonors, oleHoldings.getDonorInfo());
369         }
370         oleHoldings.setDonorInfo(donorInfoList);
371         donorInfoList = setDonorInfoToItem(oleDonors, new ArrayList<DonorInfo>());
372         oleHoldings.setDonorInfo(donorInfoList);
373         holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
374         getDocstoreClientLocator().getDocstoreClient().updateHoldings(holdings);
375     }
376 
377     /*private void performDocstoreCRUDOperationForEInstance(BibTree bibTree, OleCopy oleCopy, List<OLELinkPurapDonor> oleDonors) throws Exception {
378         String holdingsId = null;
379         List<DonorInfo> donorInfoList = new ArrayList<>();
380         for (HoldingsTree holdingsTree : bibTree.getHoldingsTrees()) {
381             if (holdingsTree.getHoldings().getHoldingsType().equals(OLEConstants.ELECTRONIC)) {
382                 holdingsId = holdingsTree.getHoldings().getId();
383                 break;
384             }
385         }
386         if (holdingsId != null) {
387             Holdings holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(holdingsId);
388             OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(holdings.getContent());
389             org.kuali.ole.docstore.common.document.content.instance.Location holdingLocation = new org.kuali.ole.docstore.common.document.content.instance.Location();
390             org.kuali.ole.docstore.common.document.content.instance.LocationLevel holdingLocationLevel = new org.kuali.ole.docstore.common.document.content.instance.LocationLevel();
391             String holdingLocationLevelCode = getLocationLevelCode(oleCopy);
392             if (null != oleCopy.getLocation()) {
393                 holdingLocation.setLocationLevel(setLocationLevels(holdingLocationLevel, holdingLocationLevelCode,
394                         oleCopy.getLocation()));
395             }
396             holdingLocation.setPrimary(OLEConstants.LOCATION_PRIMARY);
397             holdingLocation.setStatus(OLEConstants.LOCATION_STATUS);
398             oleHoldings.setLocation(holdingLocation);
399             List<OLELinkPurapDonor> oleReqDonors = new ArrayList<>();
400             for (OLELinkPurapDonor reqDonorInfo : oleDonors) {
401                 if (oleHoldings.getDonorInfo() != null && oleHoldings.getDonorInfo().size() > 0) {
402                     boolean flag = true;
403                     for (DonorInfo eHoldingsDonorInfo : oleHoldings.getDonorInfo()) {
404                         if (reqDonorInfo.getDonorCode().equals(eHoldingsDonorInfo.getDonorCode())) {
405                             flag = false;
406                             break;
407                         }
408                     }
409                     if (flag) {
410                         oleReqDonors.add(reqDonorInfo);
411                     }
412                 }
413             }
414             if (oleHoldings.getDonorInfo() != null && oleHoldings.getDonorInfo().size() > 0) {
415                 donorInfoList = setDonorInfoToItem(oleReqDonors, oleHoldings.getDonorInfo());
416             } else {
417                 donorInfoList = setDonorInfoToItem(oleDonors, oleHoldings.getDonorInfo());
418             }
419             oleHoldings.setDonorInfo(donorInfoList);
420             Holdings eHoldings = new EHoldings();
421             eHoldings.setId(holdings.getId());
422             eHoldings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
423             eHoldings.setBib(bibTree.getBib());
424             oleCopy.setInstanceId(eHoldings.getId());
425             getDocstoreClientLocator().getDocstoreClient().updateHoldings(eHoldings);
426         }
427         else {
428             createEInstance(oleCopy,oleDonors,bibTree);
429         }
430     }*/
431 
432     private void performDocstoreCRUDOperationForItemNew(String poNumber,  List<OleCopies> copies ,List<OleCopy> copyList , List<OLELinkPurapDonor> oleDonors , String itemTypeDescription, String itemTitleId,
433                                                          BibTree bibTree,String poLineItemId,String itemStatusValue, String itemLocation,
434                                                          String documentTypeName, String note, OlePurchaseOrderItem singleItem, String initiatorName) throws Exception {
435         List<org.kuali.ole.docstore.common.document.Item> itemDocuments = bibTree.getHoldingsTrees() != null && bibTree.getHoldingsTrees().size() > 0 && bibTree.getHoldingsTrees().get(0).getItems() != null
436                 ? bibTree.getHoldingsTrees().get(0).getItems() : new ArrayList<org.kuali.ole.docstore.common.document.Item>();
437         OleCopyHelperService oleCopyHelperService =  new OleCopyHelperServiceImpl();
438         HashMap<String, List<OleCopy>> copyListBasedOnLocation = oleCopyHelperService.getCopyListBasedOnLocation(copyList, itemTitleId);
439         Iterator<Map.Entry<String, List<OleCopy>>> entries = copyListBasedOnLocation.entrySet().iterator();
440         List<OleCopy> newCopyList = new ArrayList<>();
441         String location=null;
442         boolean copyFlag = false;
443         if(bibTree.getHoldingsTrees().size()>0){
444         OleHoldings oleHolding=new HoldingOlemlRecordProcessor().fromXML(bibTree.getHoldingsTrees().get(0).getHoldings().getContent());
445         StringBuffer locationName=new StringBuffer("");
446         location=docstoreUtil.getLocation(oleHolding.getLocation(),locationName);
447         }
448         int count = 0;
449         while (entries.hasNext()) {
450             Map.Entry<String, List<OleCopy>> entry = entries.next();
451             List<OleCopy> oleCopyList = entry.getValue();
452             count++;
453             if (oleCopyList != null && oleCopyList.size() > 0) {
454                 OleCopy copy = oleCopyList.get(0);
455                 if(copyListBasedOnLocation.size()==1 && oleCopyList.size() == 1 && !oleCopyList.get(0).getLocation().equalsIgnoreCase(itemLocation)){
456                     //copy.setLocation(itemLocation);
457                     updateOleHolding(bibTree.getHoldingsTrees().get(0).getHoldings().getId(),bibTree, copy);
458                     updateOleItem(poNumber, itemDocuments.get(0).getId(),poLineItemId, singleItem);
459                 }
460                 else {
461                     performUpdateForPODocuments(poNumber, bibTree, documentTypeName, poLineItemId, note, singleItem, oleCopyList, copyList, newCopyList, oleDonors, itemTypeDescription, itemStatusValue ,initiatorName);
462 
463                     /*if (bibTree.getHoldingsTrees().size()>0 && (location == null || location.isEmpty())
464                             && count == 1) {
465                         updateOleHolding(bibTree.getHoldingsTrees().get(0).getHoldings().getId(), bibTree, copy);
466                         int i = 0;
467                         for (OleCopy oleCopy : copyList) {
468                             if (oleCopy.getLocation().equals(copy.getLocation())) {
469                                 if (i == 0) {
470                                     org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemDocuments.get(0).getId());
471                                     Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
472                                     if (item.getItemType() != null) {
473                                         ItemType docstoreItemType = new ItemType();
474                                         docstoreItemType.setCodeValue(itemTypeDescription);
475                                         docstoreItemType.setFullValue(itemTypeDescription);
476                                         itemContent.setItemType(docstoreItemType);
477                                     }
478                                     itemContent.setEnumeration(oleCopy.getEnumeration());
479                                     itemContent.setCopyNumber(oleCopy.getCopyNumber());
480                                     ItemStatus itemStatus = new ItemStatus();
481                                     itemStatus.setCodeValue(itemStatusValue);
482                                     itemStatus.setFullValue(itemStatusValue);
483                                     itemContent.setItemStatus(itemStatus);
484                                     itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
485                                     if (singleItem != null) {
486                                         itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
487                                         if (singleItem.getExtendedPrice() != null) {
488                                             itemContent.setPrice(singleItem.getExtendedPrice().toString());
489                                         }
490                                         itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
491                                     }
492                                     oleCopy.setInstanceId(bibTree.getHoldingsTrees().get(0).getHoldings().getId());
493                                     oleCopy.setItemUUID(itemContent.getItemIdentifier());
494                                     List<OLELinkPurapDonor> oleReqDonors=new ArrayList<>();
495                                     List<DonorInfo> donorInfoList = new ArrayList<>();
496                                     boolean flag = true;
497                                     for (OLELinkPurapDonor reqDonorInfo : oleDonors) {
498                                         if (itemContent.getDonorInfo() != null && itemContent.getDonorInfo().size() > 0) {
499                                             for (DonorInfo itemDonorInfo : itemContent.getDonorInfo()) {
500                                                 if (itemDonorInfo.getDonorCode().equals(itemDonorInfo.getDonorCode())) {
501                                                     flag = false;
502                                                     break;
503                                                 }
504                                             }
505                                             if (flag) {
506                                                 oleReqDonors.add(reqDonorInfo);
507                                             }
508                                         }
509                                     }
510                                     if (itemContent.getDonorInfo() != null && itemContent.getDonorInfo().size() > 0) {
511                                         donorInfoList = setDonorInfoToItem(oleReqDonors, itemContent.getDonorInfo());
512                                     } else {
513                                         donorInfoList = setDonorInfoToItem(oleDonors, itemContent.getDonorInfo());
514                                     }
515                                     itemContent.setDonorInfo(donorInfoList);
516                                     item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
517                                     item.setId(itemContent.getItemIdentifier());
518                                     getDocstoreClientLocator().getDocstoreClient().updateItem(item);
519                                 }else {
520                                     Item item = setItemDetails(oleCopy,itemTypeDescription);
521                                     if (item.getItemStatus()!=null){
522                                         ItemStatus itemStatus = new ItemStatus();
523                                         itemStatus.setCodeValue(itemStatusValue);
524                                         itemStatus.setFullValue(itemStatusValue);
525                                         item.setItemStatus(itemStatus);
526                                     }
527                                     List<DonorInfo> donorInfoList = setDonorInfoToItem(oleDonors,new ArrayList<DonorInfo>());
528                                     item.setDonorInfo(donorInfoList);
529                                     item.setPurchaseOrderLineItemIdentifier(poNumber);
530                                     if (singleItem != null) {
531                                         item.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
532                                         if (singleItem.getExtendedPrice() != null) {
533                                             item.setPrice(singleItem.getExtendedPrice().toString());
534                                         }
535                                         item.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
536                                     }
537                                     org.kuali.ole.docstore.common.document.Item itemDocument = new org.kuali.ole.docstore.common.document.Item();
538                                     itemDocument.setContent(new ItemOlemlRecordProcessor().toXML(item));
539                                     itemDocument.setCategory(OLEConstants.ITEM_CATEGORY);
540                                     itemDocument.setType(OLEConstants.ITEM_TYPE);
541                                     itemDocument.setFormat(OLEConstants.ITEM_FORMAT);
542                                     itemDocument.setHolding(bibTree.getHoldingsTrees().get(0).getHoldings());
543                                     try {
544 
545                                         getDocstoreClientLocator().getDocstoreClient().createItem(itemDocument);
546                                         oleCopy.setItemUUID(itemDocument.getId());
547                                         oleCopy.setInstanceId(itemDocument.getHolding().getId());
548 
549                                     } catch (Exception ex) {
550                                         ex.printStackTrace();
551                                         throw new RuntimeException(ex);
552                                     }
553                                 }
554                             }
555                             i++;
556                         }
557                     } else {
558                     }*/
559                 }
560             }
561         }
562     }
563 
564 
565     private void performUpdateForPODocuments(String poNumber, BibTree bibTree, String documentTypeName, String poLineItemId, String note, OlePurchaseOrderItem singleItem, List<OleCopy> oleCopyList, List<OleCopy> copyList, List<OleCopy> newCopyList, List<OLELinkPurapDonor> oleDonors, String itemTypeDescription, String itemStatusValue, String initiatorName) throws Exception {
566         boolean isLocationAvailable = false;
567         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
568             updateRecordForPOVoidDocument(poNumber, bibTree, poLineItemId, note, oleCopyList, singleItem);
569             isLocationAvailable = true;
570         }
571         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
572             updateRecordForPOReOpenDocument(poNumber, bibTree, poLineItemId, copyList, singleItem);
573             isLocationAvailable = true;
574         }
575         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
576             if (oleCopyList.get(0).getItemUUID() == null && oleCopyList.get(0).getInstanceId() == null && copyList.size() > 1) {
577                 updateRecordForPOAmendmentDocument(poNumber, bibTree, copyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem, initiatorName);
578             } else {
579                 for (OleCopy oleCopy : oleCopyList) {
580                     if (oleCopy.getItemUUID() == null) {
581                         newCopyList.add(oleCopy);
582                     } else {
583                         updateOleItem(poNumber, oleCopy.getItemUUID(), poLineItemId, singleItem);
584                     }
585                     this.copyFlag = true;
586                 }
587                 createOleHoldingsTree(poNumber, bibTree, newCopyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem, initiatorName);
588             }
589             isLocationAvailable = true;
590         }
591         if (bibTree.getHoldingsTrees().size() > 0 && (documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT) ||
592                 documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT) ||
593                 documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT))) {
594             org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleCopyList.get(0).getItemUUID());
595             Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
596             if (StringUtils.isNotEmpty(poNumber)) {
597                 itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
598                 item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
599                 item.setId(itemContent.getItemIdentifier());
600                 getDocstoreClientLocator().getDocstoreClient().updateItem(item);
601             }
602             isLocationAvailable = true;
603         }
604         if (!isLocationAvailable) {
605             if (bibTree.getHoldingsTrees().size() == 1) {
606                 if (bibTree.getBib().isStaffOnly()) {
607                     bibTree.getBib().setStaffOnly(false);
608                     getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
609                 }
610             }
611             createOleHoldingsTree(poNumber, bibTree, copyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem, initiatorName);
612         }
613     }
614     /**
615      * This method will set values to Item Object and returns it to update or create Item at Docstore.
616      *
617      * @param oleCopy
618      * @param itemTypeDescription
619      * @return Item
620      */
621     public Item setItemDetails(OleCopy oleCopy, String itemTypeDescription) {
622         Item item = new Item();
623         /*
624          * Location itemLocation = new Location(); LocationLevel locationLevel = new LocationLevel(); String locationLevelCode =
625          * OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY; if (null !=
626          * copies.getLocationCopies()) { itemLocation.setLocationLevel(setLocationLevels(locationLevel, locationLevelCode,
627          * copies.getLocationCopies())); } itemLocation.setPrimary(OLEConstants.LOCATION_PRIMARY);
628          * itemLocation.setStatus(OLEConstants.LOCATION_STATUS); item.setLocation(itemLocation);
629          */
630         ItemType docstoreItemType = new ItemType();
631         docstoreItemType.setCodeValue(itemTypeDescription);
632         docstoreItemType.setFullValue(itemTypeDescription);
633         item.setItemType(docstoreItemType);
634         item.setEnumeration(oleCopy.getEnumeration());
635         item.setCopyNumber(oleCopy.getCopyNumber());
636         return item;
637     }
638 
639 
640     /**
641      * /**
642      * This method will set values to OleHoldings Object and returns it to update or create OleHoldings at Docstore.
643      *
644      * @param copy
645      * @return OleHoldings
646      */
647     public OleHoldings setHoldingDetails(OleCopy copy) throws Exception{
648         OleHoldings oleHoldings = new OleHoldings();
649         org.kuali.ole.docstore.common.document.content.instance.Location holdingLocation = new org.kuali.ole.docstore.common.document.content.instance.Location();
650         org.kuali.ole.docstore.common.document.content.instance.LocationLevel holdingLocationLevel = new org.kuali.ole.docstore.common.document.content.instance.LocationLevel();
651         String holdingLocationLevelCode = getLocationLevelCode(copy);
652         /*if (locationCopiesSplit.length == 3) {
653             holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/"
654                     + OLEConstants.LOCATION_LEVEL_CODE_CAMPUS + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
655         } else {
656             holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/"
657                     + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
658         }*/
659         /*
660          * holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
661          */
662         if (null != copy.getLocation()) {
663             holdingLocation.setLocationLevel(setLocationLevels(holdingLocationLevel, holdingLocationLevelCode,
664                     copy.getLocation()));
665         }
666         holdingLocation.setPrimary(OLEConstants.LOCATION_PRIMARY);
667         holdingLocation.setStatus(OLEConstants.LOCATION_STATUS);
668         oleHoldings.setLocation(holdingLocation);
669         return oleHoldings;
670     }
671 
672 
673 //    public WorkBibDocument performDocstoreUpdation(String itemTitleId, WorkBibDocument workBibDocument)
674 //            throws Exception {
675 //        List<WorkInstanceDocument> workInstanceDocuments = workBibDocument.getWorkInstanceDocumentList();
676 //        for (WorkInstanceDocument workInstanceDocument : workInstanceDocuments) {
677 //
678 //            if (!itemTitleId.equalsIgnoreCase(workInstanceDocument.getInstanceIdentifier())) {
679 //                deleteDocstoreRecord(OleSelectConstant.DOCSTORE_TYPE_INSTANCE,
680 //                        workInstanceDocument.getInstanceIdentifier());
681 //            } else {
682 //                if (workInstanceDocument.getItemDocumentList().size() > 1) {
683 //                    for (int i = 1; i < workInstanceDocument.getItemDocumentList().size(); i++) {
684 //                        deleteDocstoreRecord(OleSelectConstant.DOCSTORE_TYPE_ITEM, workInstanceDocument
685 //                                .getItemDocumentList().get(i).getItemIdentifier());
686 //                    }
687 //                }
688 //            }
689 //        }
690 //        List<String> itemTitleIdsList = new ArrayList<String>();
691 //        itemTitleIdsList.add(itemTitleId);
692 //        List<WorkBibDocument> workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
693 //        return workBibDocuments.get(0);
694 //    }
695 
696     public String deleteDocstoreRecord(String docType, String uuid) throws IOException {
697         String docstoreRestfulURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
698                 OLEConstants.OLE_DOCSTORE_RESTFUL_URL);
699         docstoreRestfulURL = docstoreRestfulURL.concat("/") + uuid;
700         HttpClient httpClient = new HttpClient();
701         DeleteMethod deleteMethod = new DeleteMethod(docstoreRestfulURL);
702         NameValuePair nvp1 = new NameValuePair(OLEConstants.IDENTIFIER_TYPE, OLEConstants.UUID);
703         NameValuePair nvp2 = new NameValuePair(OLEConstants.OPERATION, OLEConstants.DELETE);
704         NameValuePair category = new NameValuePair(OLEConstants.DOC_CATEGORY, OLEConstants.BIB_CATEGORY_WORK);
705         NameValuePair type = new NameValuePair(OLEConstants.DOC_TYPE, docType);
706         NameValuePair format = new NameValuePair(OLEConstants.DOC_FORMAT, OLEConstants.BIB_FORMAT_OLEML);
707         deleteMethod.setQueryString(new NameValuePair[]{nvp1, nvp2, category, type, format});
708         int statusCode = httpClient.executeMethod(deleteMethod);
709         InputStream inputStream = deleteMethod.getResponseBodyAsStream();
710         return IOUtils.toString(inputStream);
711     }
712 
713     /**
714      * Method to generate Request XML and ingest Instance record to docstore
715      *
716      * @param content
717      * @param uuid
718      * @param format
719      * @return Docstore response for Ingesting New Instance Record
720      * @throws Exception
721      */
722     public String instanceRecordCallToDocstore(String content, String uuid, String format) throws Exception {
723         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
724         String queryString = null;
725         String xmlContent = buildInstanceRequestDocXML(content, uuid, format);
726         queryString = CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xmlContent, "UTF-8");
727         return postData(docstoreURL, queryString);
728     }
729 
730     /**
731      * Method to generate Request xml for Ingesting Instance record
732      *
733      * @param xmlContent
734      * @param uuid
735      * @param format
736      * @return Request XML content
737      */
738     private String buildInstanceRequestDocXML(String xmlContent, String uuid, String format) {
739         Request requestObject = new Request();
740         RequestDocument requestDocument = new RequestDocument();
741         if (null == uuid) {
742             requestDocument.setId("1");
743             requestObject.setOperation(OLEConstants.INGEST_OPERATION);
744         } else {
745             requestDocument.setId(uuid);
746             requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
747         }
748         requestObject.setUser("editor");
749         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
750         requestDocument.setType(OLEConstants.BIB_TYPE_INSTANCE);
751         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
752 
753         requestDocument.setContent(new Content(xmlContent));
754 
755         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
756         requestDocuments.add(requestDocument);
757         requestObject.setRequestDocuments(requestDocuments);
758 
759         RequestHandler requestHandler = new RequestHandler();
760         String requestXml = requestHandler.toXML(requestObject);
761         return requestXml;
762     }
763 
764     public Response createInstanceForBib(InstanceCollection instanceCollection) {
765         String instanceXMLString = getWorkInstanceOlemlRecordProcessor().toXML(instanceCollection);
766         Response responseObject = null;
767         try {
768             String response = instanceRecordCallToDocstore(instanceXMLString, null, OLEConstants.BIB_TYPE_INSTANCE);
769             responseObject = new ResponseHandler().toObject(response);
770         } catch (Exception ex) {
771             // TODO Auto-generated catch block
772             ex.printStackTrace();
773         }
774         return responseObject;
775     }
776 
777     /*
778      * public String createInstanceForBibRecord(String bibUuid, String docType, String xmlContent) throws Exception { String
779      * docstoreURL = getConfigurationService().getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY); Request requestObject =
780      * new Request(); requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
781      * .getPrincipalId() : ""); requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION); RequestDocument requestDocument = new
782      * RequestDocument(); requestDocument.setId(bibUuid); requestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
783      * requestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_BIB);
784      * requestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_MARC); RequestDocument linkedRequestDocument = new
785      * RequestDocument(); linkedRequestDocument.setId(OLEConstants.NEW_ITEM_ID);
786      * linkedRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
787      * linkedRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_INSTANCE);
788      * linkedRequestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML); linkedRequestDocument.setContent(new Content(xmlContent));
789      * List<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
790      * linkedRequestDocuments.add(linkedRequestDocument); requestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
791      * ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>(); requestDocuments.add(requestDocument);
792      * requestObject.setRequestDocuments(requestDocuments); RequestHandler requestHandler = new RequestHandler(); String xml =
793      * requestHandler.toXML(requestObject); String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING +
794      * URLEncoder.encode(xml, "UTF-8"); return postData(docstoreURL, queryString); }
795      */
796 
797     /*
798      * public InstanceCollection getInstanceCollection(String instanceUUID) throws Exception { String responseFromDocstore =
799      * getDocstoreData(instanceUUID); InstanceCollection instanceCollection = new
800      * WorkInstanceOlemlRecordProcessor().fromXML(responseFromDocstore); return instanceCollection; }
801      */
802 
803     public String updateInstanceToDocstore(InstanceCollection instanceCollection) throws Exception {
804         String instanceXMLString = getWorkInstanceOlemlRecordProcessor().toXML(instanceCollection);
805         String instanceUUID = instanceCollection.getInstance().iterator().next().getInstanceIdentifier();
806         String response = updateInstanceRecord(instanceUUID, OLEConstants.BIB_TYPE_INSTANCE, instanceXMLString);
807         return response;
808     }
809 
810     public WorkInstanceOlemlRecordProcessor getWorkInstanceOlemlRecordProcessor() {
811         if (workInstanceOlemlRecordProcessor == null) {
812             workInstanceOlemlRecordProcessor = new WorkInstanceOlemlRecordProcessor();
813         }
814         return workInstanceOlemlRecordProcessor;
815     }
816 
817     public String getDocstoreData(String uuid) throws Exception {
818         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
819         String queryString = CHECKOUT_DOCSTORE_RECORD_QUERY_STRING + uuid;
820         String responseFromDocstore = postData(docstoreURL, queryString);
821         Response response = new ResponseHandler().toObject(responseFromDocstore);
822         String responseContent = getResponseContent(response);
823         return responseContent;
824     }
825 
826     public Response getDocstoreResponse(String uuid) throws Exception {
827         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
828         String queryString = CHECKOUT_DOCSTORE_RECORD_QUERY_STRING + uuid;
829         String responseFromDocstore = postData(docstoreURL, queryString);
830         Response response = new ResponseHandler().toObject(responseFromDocstore);
831         return response;
832     }
833 
834     public String getResponseContent(Response response) {
835         String responseString = null;
836         List<ResponseDocument> responseDocumentList = response.getDocuments();
837         for (ResponseDocument responseDocument : responseDocumentList) {
838             Content contentObj = responseDocument.getContent();
839             responseString = contentObj.getContent();
840         }
841         return responseString;
842     }
843 
844     /**
845      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
846      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
847      *
848      * @param instanceIdsList
849      * @return List<WorkBibDocument>
850      */
851 //    public List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
852 //        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
853 //        for (String instanceId : instanceIdsList) {
854 //            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
855 //            instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
856 //            instanceIdMapList.add(instanceIdMap);
857 //        }
858 //
859 //        QueryService queryService = QueryServiceImpl.getInstance();
860 //        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
861 //        try {
862 //            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
863 //        } catch (Exception ex) {
864 //            // TODO Auto-generated catch block
865 //            ex.printStackTrace();
866 //        }
867 //        return workBibDocuments;
868 //    }
869 
870     /**
871      * This method takes locationLevelCode and locationLevelName as parameters and split level name and returns as location level.
872      *
873      * @param locationLevel
874      * @param locationLevelCode
875      * @param locationLevelName
876      * @return
877      */
878     public org.kuali.ole.docstore.common.document.content.instance.LocationLevel setLocationLevels(org.kuali.ole.docstore.common.document.content.instance.LocationLevel locationLevel, String locationLevelCode,
879                                            String locationLevelName) {
880 
881         String[] levelNames = locationLevelName.split("/");
882         String[] levels = locationLevelCode.split("/");
883         locationLevel.setName(levelNames[0]);
884         locationLevel.setLevel(levels[0]);
885         String levlName = "";
886         String levl = "";
887         if (locationLevelName.contains("/") && locationLevelCode.contains("/")) {
888             levlName = locationLevelName.replace(levelNames[0] + "/", "");
889             levl = locationLevelCode.replace(levels[0] + "/", "");
890         } else {
891             levlName = locationLevelName.replace(levelNames[0], "");
892             levl = locationLevelCode.replace(levels[0], "");
893         }
894         if ((levlName != null && !levlName.equals("")) && (levl != null && !levl.equals(""))) {
895             org.kuali.ole.docstore.common.document.content.instance.LocationLevel newLocationLevel = new org.kuali.ole.docstore.common.document.content.instance.LocationLevel();
896             locationLevel.setLocationLevel(setLocationLevels(newLocationLevel, levl, levlName));
897         }
898         return locationLevel;
899     }
900 
901     public Response createItemToDocstore(String instanceUuid, org.kuali.ole.docstore.common.document.content.instance.Item item) {
902         String oleItemXMLString = new ItemOlemlRecordProcessor().toXML(item);
903         Response responseObject = null;
904         try {
905             String response = createItemForInstanceRecord(instanceUuid, OLEConstants.ITEM_DOC_TYPE, oleItemXMLString);
906             responseObject = new ResponseHandler().toObject(response);
907         } catch (Exception ex) {
908             // TODO Auto-generated catch block
909             ex.printStackTrace();
910         }
911         return responseObject;
912     }
913 
914     public String updateOleHoldingToDocstore(OleHoldings oleHoldings) throws Exception {
915         String oleHoldingXMLString = new HoldingOlemlRecordProcessor().toXML(oleHoldings);
916         String oleHoldingUUID = oleHoldings.getHoldingsIdentifier();
917 
918         String response = updateInstanceRecord(oleHoldingUUID, OLEConstants.HOLDING_DOC_TYPE, oleHoldingXMLString);
919         return response;
920     }
921 
922     public String updateOleItemToDocstore(Item item) throws Exception {
923         String oleItemXMLString = new ItemOlemlRecordProcessor().toXML(item);
924         // String itemXMLString = new UpdateDocstoreRecord().getResponseFromWorkItem(item);
925         String oleItemUUID = item.getItemIdentifier();
926         if (LOG.isDebugEnabled()) {
927             LOG.debug("oleItemUUID---------->" + oleItemUUID);
928         }
929         String response = updateInstanceRecord(oleItemUUID, OLEConstants.ITEM_DOC_TYPE, oleItemXMLString);
930         return response;
931     }
932 
933     private WorkItemOlemlRecordProcessor getWorkItemOlemlRecordProcessor() {
934         if (workItemOlemlRecordProcessor == null) {
935             workItemOlemlRecordProcessor = new WorkItemOlemlRecordProcessor();
936         }
937         return workItemOlemlRecordProcessor;
938     }
939 
940     public WorkHoldingOlemlRecordProcessor getWorkHoldingOlemlRecordProcessor() {
941         if (workHoldingOlemlRecordProcessor == null) {
942             workHoldingOlemlRecordProcessor = new WorkHoldingOlemlRecordProcessor();
943         }
944         return workHoldingOlemlRecordProcessor;
945     }
946 
947     public String updateInstanceRecord(String uuid, String docType, String xmlContent) throws Exception {
948         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
949         Request requestObject = new Request();
950         requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
951                 .getPrincipalId() : "");
952         requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
953         RequestDocument requestDocument = new RequestDocument();
954 
955         requestDocument.setId(uuid);
956         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
957         requestDocument.setType(docType); // docType should be either holdings or item
958         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
959         requestDocument.setContent(new Content(xmlContent));
960 
961         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
962         requestDocuments.add(requestDocument);
963         requestObject.setRequestDocuments(requestDocuments);
964 
965         RequestHandler requestHandler = new RequestHandler();
966         String xml = requestHandler.toXML(requestObject);
967 
968         String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xml, "UTF-8");
969 
970         return postData(docstoreURL, queryString);
971     }
972 
973     public static String postData(String target, String content) throws Exception {
974         String response = "";
975         URL url = new URL(target);
976         URLConnection conn = url.openConnection();
977         conn.setDoInput(true);
978         conn.setDoOutput(true);
979         conn.setUseCaches(false);
980         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
981 
982         Writer w = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
983         w.write(content);
984         w.close();
985         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
986         String temp;
987         while ((temp = in.readLine()) != null) {
988             response += temp + "\n";
989         }
990         in.close();
991         return response;
992     }
993 
994     /**
995      * Method to add NEW ITEM for existing Instance record
996      *
997      * @param instanceUuid
998      * @param docType
999      * @param xmlContent
1000      * @return Docstore XML response with success/failure status
1001      * @throws Exception
1002      */
1003     public String createItemForInstanceRecord(String instanceUuid, String docType, String xmlContent) throws Exception {
1004         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
1005         Request requestObject = new Request();
1006         requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
1007                 .getPrincipalId() : "");
1008         requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
1009         RequestDocument requestDocument = new RequestDocument();
1010 
1011         requestDocument.setId(instanceUuid);
1012         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
1013         requestDocument.setType(OLEConstants.BIB_TYPE_INSTANCE);
1014         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
1015 
1016 
1017         RequestDocument linkedRequestDocument = new RequestDocument();
1018         linkedRequestDocument.setId(OLEConstants.NEW_ITEM_ID);
1019         linkedRequestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
1020         linkedRequestDocument.setType(docType);
1021         linkedRequestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
1022         linkedRequestDocument.setContent(new Content(xmlContent));
1023 
1024         List<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
1025         linkedRequestDocuments.add(linkedRequestDocument);
1026         requestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
1027 
1028 
1029         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
1030         requestDocuments.add(requestDocument);
1031         requestObject.setRequestDocuments(requestDocuments);
1032 
1033         RequestHandler requestHandler = new RequestHandler();
1034         String xml = requestHandler.toXML(requestObject);
1035 
1036         String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xml, "UTF-8");
1037 
1038         return postData(docstoreURL, queryString);
1039 
1040     }
1041 
1042 
1043     public String getItemLocations(String location) {
1044         String[] locations = location.split("/");
1045         StringBuffer locationString = new StringBuffer();
1046         for (int i = locations.length - 1; i >= 1; i--) {
1047             if (i == 1) {
1048                 locationString = locationString.append(locations[i]);
1049             } else {
1050                 locationString = locationString.append(locations[i] + "/");
1051             }
1052         }
1053         return locationString.toString();
1054     }
1055 
1056 
1057 
1058     @Override
1059     public void createOrUpdateDocStoreBasedOnLocation(PurchaseOrderDocument document, PurApItem item, String currentDocumentTypeName, String note) {
1060         OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) item;
1061         try {
1062             List<String> itemTitleIdsList = new ArrayList<String>();
1063             List<BibTree> bibTrees= new ArrayList<BibTree>();
1064             itemTitleIdsList.add(olePurchaseOrderItem.getItemTitleId());
1065             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1066             for (BibTree bibTree : bibTrees) {
1067                 if (null != olePurchaseOrderItem.getItemTitleId()) {
1068                     performDocstoreUpdateForRequisitionAndPOItem(document, olePurchaseOrderItem,
1069                             bibTree, currentDocumentTypeName, note);
1070                 }
1071             }
1072         } catch (Exception e) {
1073             e.printStackTrace();
1074             throw new RuntimeException(e);
1075         }
1076     }
1077     private List<BibTree> getBibTreeDocuments(List<String> instanceIdsList) {
1078         List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
1079         for (String instanceId : instanceIdsList) {
1080             LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
1081             instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
1082             instanceIdMapList.add(instanceIdMap);
1083         }
1084         List<BibTree> bibTrees = new ArrayList<BibTree>();
1085         try {
1086             bibTrees = getWorkBibRecords(instanceIdMapList);
1087         } catch (Exception ex) {
1088             // TODO Auto-generated catch block
1089             ex.printStackTrace();
1090         }
1091         return bibTrees;
1092     }
1093     public List<BibTree> getWorkBibRecords(List<LinkedHashMap<String, String>> uuidsMapList) throws Exception {
1094         List<BibTree> bibTres = new ArrayList<BibTree>();
1095         BibTree bibTree=new BibTree();
1096         for (LinkedHashMap<String, String> uuidsMap : uuidsMapList) {
1097             if (uuidsMap.containsKey(DocType.BIB.getDescription())) {
1098                 String bibId = uuidsMap.get(DocType.BIB.getDescription());
1099                 if (LOG.isDebugEnabled()) {
1100                     LOG.debug(" bibId ---------------> " + bibId);
1101                 }
1102                 if (StringUtils.isNotBlank(bibId)) {
1103                     bibTree=getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(bibId.toString());
1104                 }
1105             }
1106             bibTres.add(bibTree);
1107         }
1108         return bibTres;
1109     }
1110     /**
1111      * Populate location levels.
1112      *
1113      * @throws Exception
1114      */
1115     public String getLocationLevelCode( OleCopy copy) throws Exception {
1116         LOG.debug("Inside the getLocationLevelCode method");
1117         StringBuffer location = new StringBuffer();
1118         StringBuffer locationLevelCode = new StringBuffer();
1119         String[] locationCopiesSplit = copy.getLocation().split("/");
1120         for(String locationCode : locationCopiesSplit){
1121             OleLocation oleLocation =getLocationByLocationCode(locationCode);
1122             if(oleLocation!=null){
1123                 OleLocationLevel oleLocationLevel =  oleLocation.getOleLocationLevel();
1124                 String levelCode = oleLocationLevel!=null && oleLocationLevel.getLevelCode()!=null ? oleLocationLevel.getLevelCode() : "" ;
1125                 setLocation(locationLevelCode,location,levelCode,oleLocation.getLocationCode(),oleLocation.getLocationName());
1126             }
1127         }
1128         return locationLevelCode.toString();
1129     }
1130 
1131     /**
1132      * sets the value for location levels in Loan Document.
1133      *
1134      * @param levelCode
1135      * @param locationCode
1136      * @throws Exception
1137      */
1138     private void setLocation(StringBuffer locationLevelCode,StringBuffer location, String levelCode, String locationCode, String locationName) throws Exception {
1139         LOG.debug("Inside the setLocation method");
1140         if (locationCode != null) {
1141             if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_SHELVING)) {
1142                 location.append(locationName);
1143                 locationLevelCode.append(levelCode);
1144             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_COLLECTION)) {
1145                 location.append(locationName + "/");
1146                 locationLevelCode.append(levelCode + "/");
1147             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_LIBRARY)) {
1148                 location.append(locationName + "/");
1149                 locationLevelCode.append(levelCode + "/");
1150             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_INSTITUTION)) {
1151                 location.append(locationName + "/");
1152                 locationLevelCode.append(levelCode + "/");
1153             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_CAMPUS)) {
1154                 location.append(locationName + "/");
1155                 locationLevelCode.append(levelCode + "/");
1156             }
1157         }
1158     }
1159 
1160     /**
1161      * This method returns location using location code.
1162      *
1163      * @param locationCode
1164      * @return
1165      * @throws Exception
1166      */
1167     private OleLocation getLocationByLocationCode(String locationCode) throws Exception {
1168         LOG.debug("Inside the getLocationByLocationCode method");
1169         Map barMap = new HashMap();
1170         barMap.put(org.kuali.ole.OLEConstants.LOC_CD, locationCode);
1171         List<OleLocation> matchingLocation = (List<OleLocation>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLocation.class, barMap);
1172         return matchingLocation.size()>0 ? matchingLocation.get(0) : null;
1173     }
1174 
1175 
1176     /*@Override
1177     public void updateItemNote(PurApItem item, String note) {
1178         OleRequisitionItem oleRequisitionItem = (OleRequisitionItem) item;
1179         try {
1180             List<String> itemTitleIdsList = new ArrayList<String>();
1181             List<BibTree> bibTrees = new ArrayList<BibTree>();
1182             itemTitleIdsList.add(oleRequisitionItem.getItemTitleId());
1183             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1184             for (BibTree bibTree : bibTrees) {
1185                 if (null != oleRequisitionItem.getItemTitleId()) {
1186                     performDocstoreUpdateForRequisitionItemRecord(oleRequisitionItem,
1187                             bibTree, note);
1188                 }
1189             }
1190         } catch (Exception e) {
1191             e.printStackTrace();
1192             throw new RuntimeException(e);
1193         }
1194     }
1195 
1196     private void performDocstoreUpdateForRequisitionItemRecord(OleRequisitionItem oleRequisitionItem , BibTree bibTree, String note) throws Exception {
1197         List<OleCopy> copyList = oleRequisitionItem.getCopyList();
1198         String itemTitleId = oleRequisitionItem.getItemTitleId();
1199         OleCopyHelperService oleCopyHelperService =  new OleCopyHelperServiceImpl();
1200         HashMap<String, List<OleCopy>> copyListBasedOnLocation = oleCopyHelperService.getCopyListBasedOnLocation(copyList, itemTitleId);
1201         Iterator<Map.Entry<String, List<OleCopy>>> entries = copyListBasedOnLocation.entrySet().iterator();
1202         int count = 0;
1203         if (copyList.size() == 0) {
1204             OleCopy oleCopy = new OleCopy();
1205             oleCopy.setLocation(oleRequisitionItem.getItemLocation());
1206             if (bibTree.getHoldingsTrees().size() == 1) {
1207                 updateOleHoldingStaffOnly(bibTree,oleCopy,true);
1208                 bibTree.getBib().setStaffOnly(true);
1209                 getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1210             }
1211             for (int items=0; items < bibTree.getHoldingsTrees().size(); items++) {
1212                 updateOleItemStaffOnly(bibTree.getHoldingsTrees().get(items).getItems().get(0).getId(),null,note,true);
1213                 oleCopy.setReqDocNum(null);
1214                 oleCopy.setReqItemId(null);
1215             }
1216         }
1217         while (entries.hasNext()) {
1218             Map.Entry<String, List<OleCopy>> entry = entries.next();
1219             List<OleCopy> oleCopyList = entry.getValue();
1220             count++;
1221             if (oleCopyList != null && oleCopyList.size() > 0) {
1222                 if (bibTree.getHoldingsTrees().size() == 1) {
1223                     OleCopy copy = oleCopyList.get(0);
1224                     updateOleHoldingStaffOnly(bibTree,copy,true);
1225                     bibTree.getBib().setStaffOnly(true);
1226                     getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1227                 }
1228                 for (OleCopy oleCopy : copyList) {
1229                     for (int items=0; items < bibTree.getHoldingsTrees().size(); items++) {
1230                         for (int singleItem=0; singleItem < bibTree.getHoldingsTrees().get(items).getItems().size(); singleItem++) {
1231                             if (oleCopy.getItemUUID().equalsIgnoreCase(bibTree.getHoldingsTrees().get(items).getItems().get(singleItem).getId())) {
1232                                 if (!bibTree.getHoldingsTrees().get(items).getItems().get(singleItem).isStaffOnly()) {
1233                                     updateOleItemStaffOnly(oleCopy.getItemUUID(),null,note,true);
1234                                     oleCopy.setReqDocNum(null);
1235                                     oleCopy.setReqItemId(null);
1236                                 }
1237                             }
1238 
1239                         }
1240                     }
1241                 }
1242             }
1243         }
1244 
1245     }*/
1246 
1247     private List<DonorInfo> setDonorInfoToItem(List<OLELinkPurapDonor> oleDonors,List<DonorInfo> donorInfoList){
1248         for (OLELinkPurapDonor oleLinkPurapDonor : oleDonors) {
1249             DonorInfo donorInfo = new DonorInfo();
1250             donorInfo.setDonorCode(oleLinkPurapDonor.getDonorCode());
1251             Map donorMap = new HashMap();
1252             donorMap.put(OLEConstants.DONOR_CODE, oleLinkPurapDonor.getDonorCode());
1253             OLEDonor oleDonor = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEDonor.class, donorMap);
1254             if (oleDonor != null) {
1255                 if (StringUtils.isNotEmpty(oleDonor.getDonorNote()))
1256                     donorInfo.setDonorNote(oleDonor.getDonorNote());
1257                 if (StringUtils.isNotEmpty(oleDonor.getDonorPublicDisplay()))
1258                     donorInfo.setDonorPublicDisplay(oleDonor.getDonorPublicDisplay());
1259             }
1260             donorInfoList.add(donorInfo);
1261         }
1262         return donorInfoList;
1263     }
1264 
1265     @Override
1266     public void updateItemLocation(PurchaseOrderDocument document, PurApItem item) {
1267         OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) item;
1268         try {
1269             List<String> itemTitleIdsList = new ArrayList<String>();
1270             List<BibTree> bibTrees= new ArrayList<BibTree>();
1271             String poLineItemId =  olePurchaseOrderItem.getItemIdentifier()!=null?olePurchaseOrderItem.getItemIdentifier().toString():null;
1272             itemTitleIdsList.add(olePurchaseOrderItem.getItemTitleId());
1273             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1274             for (BibTree bibTree : bibTrees) {
1275                 if (null != olePurchaseOrderItem.getItemTitleId()) {
1276                     if (olePurchaseOrderItem.isItemLocationChangeFlag()) {
1277                         if (StringUtils.isNotBlank(olePurchaseOrderItem.getItemLocation()) && olePurchaseOrderItem.getCopyList().size() == 1) {
1278                             if( bibTree.getHoldingsTrees().size()>0 ){
1279                                 OleCopy copy = olePurchaseOrderItem.getCopyList().get(0);
1280                                 copy.setLocation(olePurchaseOrderItem.getItemLocation());
1281                                 updateOleHolding(copy.getInstanceId(),bibTree, copy);
1282                                 updateOleItem(document.getPurapDocumentIdentifier().toString(), olePurchaseOrderItem.getCopyList().get(0).getItemUUID(),poLineItemId, olePurchaseOrderItem);
1283                             }
1284                         }
1285                     }
1286                 }
1287             }
1288         } catch (Exception e) {
1289             e.printStackTrace();
1290             throw new RuntimeException(e);
1291         }
1292     }
1293 
1294     private void updateOleHoldingStaffOnly(String holdingId, BibTree bibTree, OleCopy copy,boolean staffOnly) throws Exception {
1295         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1296         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1297         oleHoldings.setHoldingsIdentifier(holdingId);
1298         Holdings newHoldings=new PHoldings();
1299         newHoldings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1300         newHoldings.setStaffOnly(staffOnly);
1301         newHoldings.setId(holdingId);
1302         newHoldings.setBib(bibTree.getBib());
1303         getDocstoreClientLocator().getDocstoreClient().updateHoldings(newHoldings);
1304     }
1305 
1306     private void updateOleHolding(String holdingId, BibTree bibTree, OleCopy copy) throws Exception {
1307         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1308         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1309         oleHoldings.setHoldingsIdentifier(holdingId);
1310         Holdings holdings=new PHoldings();
1311         holdings.setId(holdingId);
1312         holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1313         holdings.setBib(bibTree.getBib());
1314         getDocstoreClientLocator().getDocstoreClient().updateHoldings(holdings);
1315     }
1316 
1317     private void updateOleItem(String poNumber, String itemId, String poLineItemId, OlePurchaseOrderItem singleItem) throws Exception {
1318         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemId);
1319         Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
1320         List<DonorInfo> donorInfoList = setDonorInfoToItem(singleItem.getOleDonors(), new ArrayList<DonorInfo>());
1321         itemContent.setDonorInfo(donorInfoList);
1322         itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
1323         if (singleItem != null) {
1324             itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1325             if (singleItem.getExtendedPrice() != null) {
1326                 itemContent.setPrice(singleItem.getExtendedPrice().toString());
1327             }
1328             itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1329         }
1330         itemContent.setItemIdentifier(itemId);
1331         item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
1332         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
1333     }
1334 
1335     private void updateOleItemStaffOnly(String poNumber, String itemId, String poLineItemId, String note, boolean staffOnly, OlePurchaseOrderItem singleItem) throws Exception {
1336         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemId);
1337         Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
1338         if (StringUtils.isNotEmpty(poNumber)) {
1339             itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
1340         }
1341         if (singleItem != null) {
1342             itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1343             if (singleItem.getExtendedPrice() != null) {
1344                 itemContent.setPrice(singleItem.getExtendedPrice().toString());
1345             }
1346             itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1347         }
1348         itemContent.setItemIdentifier(itemId);
1349         if (StringUtils.isNotEmpty(note)) {
1350             List<Note> noteList = itemContent.getNote()!=null ? itemContent.getNote() : (List<Note>) new ArrayList<Note>();
1351             Note noteObj = new Note();
1352             noteObj.setType(OLEConstants.NON_PUBLIC);
1353             noteObj.setValue(note);
1354             noteList.add(noteObj);
1355             itemContent.setNote(noteList);
1356         }
1357         item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
1358         item.setStaffOnly(staffOnly);
1359         item.setId(itemContent.getItemIdentifier());
1360         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
1361     }
1362 
1363     private void updateRecordForPOVoidDocument(String poNumber, BibTree bibTree, String poLineItemId, String note ,List<OleCopy> copyList, OlePurchaseOrderItem singleItem) throws Exception {
1364         OleCopy copy = copyList.get(0);
1365         if (bibTree.getHoldingsTrees().size() == 1 && copyList.size()==1) {
1366             bibTree.getBib().setStaffOnly(true);
1367             getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1368         }
1369         if (copyList.size()==1) {
1370             updateOleHoldingStaffOnly(copy.getInstanceId(),bibTree,copy,true);
1371         }
1372         for (OleCopy oleCopy : copyList) {
1373             updateOleItemStaffOnly(poNumber, oleCopy.getItemUUID(),poLineItemId,note,true, singleItem);
1374             oleCopy.setReqDocNum(null);
1375             oleCopy.setReqItemId(null);
1376         }
1377     }
1378 
1379     private void updateRecordForPOReOpenDocument(String poNumber, BibTree bibTree, String poLineItemId, List<OleCopy> copyList, OlePurchaseOrderItem singleItem) throws Exception {
1380         OleCopy copy = copyList.get(0);
1381         if (bibTree.getBib().getId().equalsIgnoreCase(OLEConstants.TRUE)) {
1382             bibTree.getBib().setStaffOnly(false);
1383             getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1384         }
1385         if (copyList.size()==1) {
1386             updateOleHoldingStaffOnly(copy.getInstanceId(),bibTree,copy,false);
1387         }
1388         for (OleCopy oleCopy : copyList) {
1389             updateOleItemStaffOnly(poNumber, oleCopy.getItemUUID(),poLineItemId,null,false, singleItem);
1390             oleCopy.setReqDocNum(null);
1391             oleCopy.setReqItemId(null);
1392         }
1393     }
1394 
1395     private void updateRecordForPOAmendmentDocument(String poNumber, BibTree bibTree,List<OleCopy> copyList, String poLineItemId,List<OLELinkPurapDonor> oleDonors,List<OleCopy> oleCopyList,
1396                                                     String itemTypeDescription,String itemStatusValue, OlePurchaseOrderItem singleItem, String initiatorName) throws Exception {
1397         OleCopy copy = oleCopyList.get(0);
1398         if (copyList.size()>1) {
1399             if (!this.copyFlag) {
1400                 List <OleCopy> newCopyList = new ArrayList<>();
1401                 int j=0;
1402                 for (OleCopy newCopy : oleCopyList) {
1403                     if (!this.newCopyFlag) { // existing record's location  is updated with First copy from copyList
1404                         updateOleHolding(bibTree.getHoldingsTrees().get(0).getHoldings().getId(),bibTree, newCopy);
1405                         if (bibTree.getHoldingsTrees().get(0).getItems().size()==1) {
1406                             updateOleItem(poNumber, bibTree.getHoldingsTrees().get(0).getItems().get(0).getId(),poLineItemId, singleItem);
1407                             newCopy.setInstanceId(bibTree.getHoldingsTrees().get(0).getHoldings().getId());
1408                             newCopy.setItemUUID(bibTree.getHoldingsTrees().get(0).getItems().get(0).getId());
1409                             for (int copyCnt=0; copyCnt<oleCopyList.size(); copyCnt++) {
1410                                 if (!newCopy.getCopyId().equals(oleCopyList.get(copyCnt).getCopyId())) {
1411                                     newCopyList.add(oleCopyList.get(copyCnt));
1412                                 }
1413                             }
1414                             this.copyCount++;
1415                         }
1416                         else {
1417                             int itemRecord=0;
1418                             for (int copyRecord=0;copyRecord<oleCopyList.size();) {
1419                                 if ( itemRecord<bibTree.getHoldingsTrees().get(0).getItems().size()) {
1420                                     updateOleItem(poNumber, bibTree.getHoldingsTrees().get(0).getItems().get(itemRecord).getId(), poLineItemId, singleItem);
1421                                     oleCopyList.get(copyRecord).setInstanceId(bibTree.getHoldingsTrees().get(0).getHoldings().getId());
1422                                     oleCopyList.get(copyRecord).setItemUUID(bibTree.getHoldingsTrees().get(0).getItems().get(itemRecord).getId());
1423                                     this.copyCount++;itemRecord++;copyRecord++;
1424                                 }
1425                                 if(itemRecord==bibTree.getHoldingsTrees().get(0).getItems().size()){
1426                                     if (copyRecord < oleCopyList.size()) {
1427                                         newCopyList.add(oleCopyList.get(copyRecord));
1428                                         copyRecord++;
1429                                     }
1430                                 }
1431                             }
1432                         }
1433                         this.newCopyFlag = true;
1434                     } else {
1435                         if (newCopyList.size()>0) {
1436 
1437                             /*List<OleCopy> newCopies = new ArrayList();
1438                             for (int oleCopy=0; oleCopy<newCopyList.size();) {
1439                                 newCopies.add(newCopyList.get(oleCopy));
1440                                 createOleHoldingsTree(bibTree,copyList,poLineItemId,oleDonors,newCopies,itemTypeDescription,itemStatusValue);
1441                                 newCopies.clear();
1442                                 oleCopy++;
1443                             }*/
1444                             createOleHoldingsTree(poNumber, bibTree,newCopyList,poLineItemId,oleDonors,oleCopyList,itemTypeDescription,itemStatusValue,singleItem, initiatorName);
1445                         }
1446                         if (this.copyCount==oleCopyList.size()) {
1447                             break;
1448                         }
1449                     }
1450                 }
1451                 this.copyFlag = true;
1452             } else {  // new record's are created with its respective locations.
1453                 createOleHoldingsTree(poNumber, bibTree,copyList,poLineItemId,oleDonors,oleCopyList,itemTypeDescription,itemStatusValue, singleItem, initiatorName);
1454             }
1455         }
1456     }
1457 
1458     public void createOleHoldingsTree(String poNumber, BibTree bibTree,List<OleCopy> copyList, String poLineItemId,List<OLELinkPurapDonor> oleDonors,List<OleCopy> oleCopyList,
1459                                         String itemTypeDescription,String itemStatusValue, OlePurchaseOrderItem singleItem, String initiatorName) throws Exception {
1460         OleCopy copy = oleCopyList.get(0);
1461         Holdings pHoldings = new PHoldings();
1462         if (StringUtils.isNotBlank(copy.getInstanceId())) {
1463             pHoldings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(copy.getInstanceId());
1464         }
1465         List<org.kuali.ole.docstore.common.document.Item> itemList = new ArrayList<org.kuali.ole.docstore.common.document.Item>();
1466         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1467         oleHoldings.setHoldingsIdentifier(null);
1468         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1469         List<Integer> copyIdList = new ArrayList<>();
1470         for (OleCopy oleCopy : copyList) {
1471             if (oleCopy.getLocation().equals(copy.getLocation())) {
1472                 Item item = setItemDetails(oleCopy, itemTypeDescription);
1473                 ItemStatus itemStatus = new ItemStatus();
1474                 itemStatus.setCodeValue(itemStatusValue);
1475                 itemStatus.setFullValue(itemStatusValue);
1476                 item.setItemStatus(itemStatus);
1477                 item.setPurchaseOrderLineItemIdentifier(poNumber);
1478                 if (singleItem != null) {
1479                     item.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1480                     if (singleItem.getExtendedPrice() != null) {
1481                         item.setPrice(singleItem.getExtendedPrice().toString());
1482                     }
1483                     item.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1484                 }
1485                 List<DonorInfo> donorInfoList = setDonorInfoToItem(oleDonors, new ArrayList<DonorInfo>());
1486                 item.setDonorInfo(donorInfoList);
1487                 org.kuali.ole.docstore.common.document.Item itemDocument = new org.kuali.ole.docstore.common.document.Item();
1488                 itemDocument.setContent(new ItemOlemlRecordProcessor().toXML(item));
1489                 itemDocument.setCreatedBy(initiatorName);
1490                 itemDocument.setCategory(OLEConstants.ITEM_CATEGORY);
1491                 itemDocument.setType(OLEConstants.ITEM_TYPE);
1492                 itemDocument.setFormat(OLEConstants.ITEM_FORMAT);
1493                 if (StringUtils.isNotBlank(copy.getInstanceId())) {
1494                     itemDocument.setHolding(pHoldings);
1495                     getDocstoreClientLocator().getDocstoreClient().createItem(itemDocument);
1496                 } else {
1497                     itemList.add(itemDocument);
1498                 }
1499                 copyIdList.add(oleCopy.getCopyId());
1500             }
1501         }
1502         HoldingsTree holdingsTree = new HoldingsTree();
1503         if (StringUtils.isBlank(copy.getInstanceId())) {
1504             holdingsTree.getItems().addAll(itemList);
1505             Holdings holdings = new PHoldings();
1506             holdings.setCategory(DocCategory.WORK.getCode());
1507             holdings.setType(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode());
1508             holdings.setFormat(org.kuali.ole.docstore.common.document.content.enums.DocFormat.OLEML.getCode());
1509             holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1510             holdings.setCreatedBy(initiatorName);
1511             Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(bibTree.getBib().getId());
1512             holdings.setBib(bib);
1513             holdingsTree.setHoldings(holdings);
1514             getDocstoreClientLocator().getDocstoreClient().createHoldingsTree(holdingsTree);
1515         } else {
1516             holdingsTree = getDocstoreClientLocator().getDocstoreClient().retrieveHoldingsTree(copy.getInstanceId());
1517         }
1518         int i = 0;
1519         for (org.kuali.ole.docstore.common.document.Item item : holdingsTree.getItems()) {
1520             for (OleCopy oleCopy : copyList) {
1521                 if (copyIdList != null && copyIdList.size() > i && copyIdList.get(i).equals(oleCopy.getCopyId())) {
1522                     oleCopy.setInstanceId(holdingsTree.getHoldings().getId());
1523                     oleCopy.setItemUUID(item.getId());
1524                     this.copyCount++;
1525                     if (LOG.isDebugEnabled()) {
1526                         LOG.debug("Instance UUID" + holdingsTree.getHoldings().getId() + "****** Item UUID" + item.getId());
1527                     }
1528                 }
1529             }
1530             i++;
1531 
1532         }
1533     }
1534 
1535     private String populateFundCodes(List<PurApAccountingLine> purApAccountingLines) {
1536         StringBuffer fundCode = new StringBuffer();
1537         List fundCodeList = new ArrayList();
1538         if (purApAccountingLines != null && purApAccountingLines.size() > 0) {
1539             for (PurApAccountingLine accountingLine : purApAccountingLines) {
1540                 Map map = new HashMap();
1541                 map.put(org.kuali.ole.OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
1542                 map.put(org.kuali.ole.OLEConstants.OBJECT_CODE, accountingLine.getFinancialObjectCode());
1543                 OleVendorAccountInfo oleVendorAccountInfo = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleVendorAccountInfo.class, map);
1544                 if (oleVendorAccountInfo != null && !fundCodeList.contains(oleVendorAccountInfo.getVendorRefNumber())) {
1545                     fundCodeList.add(oleVendorAccountInfo.getVendorRefNumber());
1546                     fundCode.append(oleVendorAccountInfo.getVendorRefNumber());
1547                     fundCode.append(org.kuali.ole.OLEConstants.COMMA);
1548                     fundCode.append(' ');
1549                 }
1550             }
1551         }
1552         if (fundCode.length() > 0) {
1553             fundCode.deleteCharAt(fundCode.length() - 2);
1554             return fundCode.toString();
1555         }
1556         return null;
1557     }
1558 
1559     public boolean isValidLocation(String location) {
1560         List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
1561         if (locationList != null && locationList.size() > 0) {
1562             for (String locationValue : locationList) {
1563                 if (locationValue.equalsIgnoreCase(location)) {
1564                     return true;
1565                 }
1566             }
1567         }
1568         return false;
1569     }
1570 
1571 }