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