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_DOCUMENT)) {
548           //  updateRecordForPODocument(poNumber, bibTree, poLineItemId, note, oleCopyList, singleItem);
549             isLocationAvailable = true;
550         }
551         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
552             updateRecordForPOVoidDocument(poNumber, bibTree, poLineItemId, note, oleCopyList, singleItem);
553             isLocationAvailable = true;
554         }
555         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
556             updateRecordForPOReOpenDocument(poNumber, bibTree, poLineItemId, copyList, singleItem);
557             isLocationAvailable = true;
558         }
559         if (bibTree.getHoldingsTrees().size() > 0 && documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
560             if (oleCopyList.get(0).getItemUUID() == null && oleCopyList.get(0).getInstanceId() == null && copyList.size() > 1) {
561                 updateRecordForPOAmendmentDocument(poNumber, bibTree, copyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem);
562             } else {
563                 for (OleCopy oleCopy : oleCopyList) {
564                     if (oleCopy.getItemUUID() == null) {
565                         newCopyList.add(oleCopy);
566                     } else {
567                         updateOleItem(poNumber, oleCopy.getItemUUID(), poLineItemId, singleItem);
568                     }
569                     this.copyFlag = true;
570                 }
571                 createOleHoldingsTree(poNumber, bibTree, newCopyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem);
572             }
573             isLocationAvailable = true;
574         }
575         if (bibTree.getHoldingsTrees().size() > 0 && (documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT) ||
576                 documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT) ||
577                 documentTypeName.equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT))) {
578             org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleCopyList.get(0).getItemUUID());
579             Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
580             if (StringUtils.isNotEmpty(poNumber)) {
581                 itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
582                 item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
583                 item.setId(itemContent.getItemIdentifier());
584                 getDocstoreClientLocator().getDocstoreClient().updateItem(item);
585             }
586             isLocationAvailable = true;
587         }
588         if (!isLocationAvailable) {
589             if (bibTree.getHoldingsTrees().size() == 1) {
590                 if (bibTree.getBib().isStaffOnly()) {
591                     bibTree.getBib().setStaffOnly(false);
592                     getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
593                 }
594             }
595             createOleHoldingsTree(poNumber, bibTree, copyList, poLineItemId, oleDonors, oleCopyList, itemTypeDescription, itemStatusValue, singleItem);
596         }
597     }
598     /**
599      * This method will set values to Item Object and returns it to update or create Item at Docstore.
600      *
601      * @param oleCopy
602      * @param itemTypeDescription
603      * @return Item
604      */
605     public Item setItemDetails(OleCopy oleCopy, String itemTypeDescription) {
606         Item item = new Item();
607         /*
608          * Location itemLocation = new Location(); LocationLevel locationLevel = new LocationLevel(); String locationLevelCode =
609          * OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY; if (null !=
610          * copies.getLocationCopies()) { itemLocation.setLocationLevel(setLocationLevels(locationLevel, locationLevelCode,
611          * copies.getLocationCopies())); } itemLocation.setPrimary(OLEConstants.LOCATION_PRIMARY);
612          * itemLocation.setStatus(OLEConstants.LOCATION_STATUS); item.setLocation(itemLocation);
613          */
614         ItemType docstoreItemType = new ItemType();
615         docstoreItemType.setCodeValue(itemTypeDescription);
616         docstoreItemType.setFullValue(itemTypeDescription);
617         item.setItemType(docstoreItemType);
618         item.setEnumeration(oleCopy.getEnumeration());
619         item.setCopyNumber(oleCopy.getCopyNumber());
620         return item;
621     }
622 
623 
624     /**
625      * /**
626      * This method will set values to OleHoldings Object and returns it to update or create OleHoldings at Docstore.
627      *
628      * @param copy
629      * @return OleHoldings
630      */
631     public OleHoldings setHoldingDetails(OleCopy copy) throws Exception{
632         OleHoldings oleHoldings = new OleHoldings();
633         org.kuali.ole.docstore.common.document.content.instance.Location holdingLocation = new org.kuali.ole.docstore.common.document.content.instance.Location();
634         org.kuali.ole.docstore.common.document.content.instance.LocationLevel holdingLocationLevel = new org.kuali.ole.docstore.common.document.content.instance.LocationLevel();
635         String holdingLocationLevelCode = getLocationLevelCode(copy);
636         /*if (locationCopiesSplit.length == 3) {
637             holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/"
638                     + OLEConstants.LOCATION_LEVEL_CODE_CAMPUS + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
639         } else {
640             holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/"
641                     + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
642         }*/
643         /*
644          * holdingLocationLevelCode = OLEConstants.LOCATION_LEVEL_CODE_INSTITUTION + "/" + OLEConstants.LOCATION_LEVEL_CODE_LIBRARY;
645          */
646         if (null != copy.getLocation()) {
647             holdingLocation.setLocationLevel(setLocationLevels(holdingLocationLevel, holdingLocationLevelCode,
648                     copy.getLocation()));
649         }
650         holdingLocation.setPrimary(OLEConstants.LOCATION_PRIMARY);
651         holdingLocation.setStatus(OLEConstants.LOCATION_STATUS);
652         oleHoldings.setLocation(holdingLocation);
653         return oleHoldings;
654     }
655 
656 
657 //    public WorkBibDocument performDocstoreUpdation(String itemTitleId, WorkBibDocument workBibDocument)
658 //            throws Exception {
659 //        List<WorkInstanceDocument> workInstanceDocuments = workBibDocument.getWorkInstanceDocumentList();
660 //        for (WorkInstanceDocument workInstanceDocument : workInstanceDocuments) {
661 //
662 //            if (!itemTitleId.equalsIgnoreCase(workInstanceDocument.getInstanceIdentifier())) {
663 //                deleteDocstoreRecord(OleSelectConstant.DOCSTORE_TYPE_INSTANCE,
664 //                        workInstanceDocument.getInstanceIdentifier());
665 //            } else {
666 //                if (workInstanceDocument.getItemDocumentList().size() > 1) {
667 //                    for (int i = 1; i < workInstanceDocument.getItemDocumentList().size(); i++) {
668 //                        deleteDocstoreRecord(OleSelectConstant.DOCSTORE_TYPE_ITEM, workInstanceDocument
669 //                                .getItemDocumentList().get(i).getItemIdentifier());
670 //                    }
671 //                }
672 //            }
673 //        }
674 //        List<String> itemTitleIdsList = new ArrayList<String>();
675 //        itemTitleIdsList.add(itemTitleId);
676 //        List<WorkBibDocument> workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
677 //        return workBibDocuments.get(0);
678 //    }
679 
680     public String deleteDocstoreRecord(String docType, String uuid) throws IOException {
681         String docstoreRestfulURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
682                 OLEConstants.OLE_DOCSTORE_RESTFUL_URL);
683         docstoreRestfulURL = docstoreRestfulURL.concat("/") + uuid;
684         HttpClient httpClient = new HttpClient();
685         DeleteMethod deleteMethod = new DeleteMethod(docstoreRestfulURL);
686         NameValuePair nvp1 = new NameValuePair(OLEConstants.IDENTIFIER_TYPE, OLEConstants.UUID);
687         NameValuePair nvp2 = new NameValuePair(OLEConstants.OPERATION, OLEConstants.DELETE);
688         NameValuePair category = new NameValuePair(OLEConstants.DOC_CATEGORY, OLEConstants.BIB_CATEGORY_WORK);
689         NameValuePair type = new NameValuePair(OLEConstants.DOC_TYPE, docType);
690         NameValuePair format = new NameValuePair(OLEConstants.DOC_FORMAT, OLEConstants.BIB_FORMAT_OLEML);
691         deleteMethod.setQueryString(new NameValuePair[]{nvp1, nvp2, category, type, format});
692         int statusCode = httpClient.executeMethod(deleteMethod);
693         InputStream inputStream = deleteMethod.getResponseBodyAsStream();
694         return IOUtils.toString(inputStream);
695     }
696 
697     /**
698      * Method to generate Request XML and ingest Instance record to docstore
699      *
700      * @param content
701      * @param uuid
702      * @param format
703      * @return Docstore response for Ingesting New Instance Record
704      * @throws Exception
705      */
706     public String instanceRecordCallToDocstore(String content, String uuid, String format) throws Exception {
707         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
708         String queryString = null;
709         String xmlContent = buildInstanceRequestDocXML(content, uuid, format);
710         queryString = CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xmlContent, "UTF-8");
711         return postData(docstoreURL, queryString);
712     }
713 
714     /**
715      * Method to generate Request xml for Ingesting Instance record
716      *
717      * @param xmlContent
718      * @param uuid
719      * @param format
720      * @return Request XML content
721      */
722     private String buildInstanceRequestDocXML(String xmlContent, String uuid, String format) {
723         Request requestObject = new Request();
724         RequestDocument requestDocument = new RequestDocument();
725         if (null == uuid) {
726             requestDocument.setId("1");
727             requestObject.setOperation(OLEConstants.INGEST_OPERATION);
728         } else {
729             requestDocument.setId(uuid);
730             requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
731         }
732         requestObject.setUser("editor");
733         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
734         requestDocument.setType(OLEConstants.BIB_TYPE_INSTANCE);
735         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
736 
737         requestDocument.setContent(new Content(xmlContent));
738 
739         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
740         requestDocuments.add(requestDocument);
741         requestObject.setRequestDocuments(requestDocuments);
742 
743         RequestHandler requestHandler = new RequestHandler();
744         String requestXml = requestHandler.toXML(requestObject);
745         return requestXml;
746     }
747 
748     public Response createInstanceForBib(InstanceCollection instanceCollection) {
749         String instanceXMLString = getWorkInstanceOlemlRecordProcessor().toXML(instanceCollection);
750         Response responseObject = null;
751         try {
752             String response = instanceRecordCallToDocstore(instanceXMLString, null, OLEConstants.BIB_TYPE_INSTANCE);
753             responseObject = new ResponseHandler().toObject(response);
754         } catch (Exception ex) {
755             // TODO Auto-generated catch block
756             ex.printStackTrace();
757         }
758         return responseObject;
759     }
760 
761     /*
762      * public String createInstanceForBibRecord(String bibUuid, String docType, String xmlContent) throws Exception { String
763      * docstoreURL = getConfigurationService().getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY); Request requestObject =
764      * new Request(); requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
765      * .getPrincipalId() : ""); requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION); RequestDocument requestDocument = new
766      * RequestDocument(); requestDocument.setId(bibUuid); requestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
767      * requestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_BIB);
768      * requestDocument.setFormat(OleSelectConstant.DOCSTORE_FORMAT_MARC); RequestDocument linkedRequestDocument = new
769      * RequestDocument(); linkedRequestDocument.setId(OLEConstants.NEW_ITEM_ID);
770      * linkedRequestDocument.setCategory(OleSelectConstant.DOCSTORE_CATEGORY_WORK);
771      * linkedRequestDocument.setType(OleSelectConstant.DOCSTORE_TYPE_INSTANCE);
772      * linkedRequestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML); linkedRequestDocument.setContent(new Content(xmlContent));
773      * List<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
774      * linkedRequestDocuments.add(linkedRequestDocument); requestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
775      * ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>(); requestDocuments.add(requestDocument);
776      * requestObject.setRequestDocuments(requestDocuments); RequestHandler requestHandler = new RequestHandler(); String xml =
777      * requestHandler.toXML(requestObject); String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING +
778      * URLEncoder.encode(xml, "UTF-8"); return postData(docstoreURL, queryString); }
779      */
780 
781     /*
782      * public InstanceCollection getInstanceCollection(String instanceUUID) throws Exception { String responseFromDocstore =
783      * getDocstoreData(instanceUUID); InstanceCollection instanceCollection = new
784      * WorkInstanceOlemlRecordProcessor().fromXML(responseFromDocstore); return instanceCollection; }
785      */
786 
787     public String updateInstanceToDocstore(InstanceCollection instanceCollection) throws Exception {
788         String instanceXMLString = getWorkInstanceOlemlRecordProcessor().toXML(instanceCollection);
789         String instanceUUID = instanceCollection.getInstance().iterator().next().getInstanceIdentifier();
790         String response = updateInstanceRecord(instanceUUID, OLEConstants.BIB_TYPE_INSTANCE, instanceXMLString);
791         return response;
792     }
793 
794     public WorkInstanceOlemlRecordProcessor getWorkInstanceOlemlRecordProcessor() {
795         if (workInstanceOlemlRecordProcessor == null) {
796             workInstanceOlemlRecordProcessor = new WorkInstanceOlemlRecordProcessor();
797         }
798         return workInstanceOlemlRecordProcessor;
799     }
800 
801     public String getDocstoreData(String uuid) throws Exception {
802         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
803         String queryString = CHECKOUT_DOCSTORE_RECORD_QUERY_STRING + uuid;
804         String responseFromDocstore = postData(docstoreURL, queryString);
805         Response response = new ResponseHandler().toObject(responseFromDocstore);
806         String responseContent = getResponseContent(response);
807         return responseContent;
808     }
809 
810     public Response getDocstoreResponse(String uuid) throws Exception {
811         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
812         String queryString = CHECKOUT_DOCSTORE_RECORD_QUERY_STRING + uuid;
813         String responseFromDocstore = postData(docstoreURL, queryString);
814         Response response = new ResponseHandler().toObject(responseFromDocstore);
815         return response;
816     }
817 
818     public String getResponseContent(Response response) {
819         String responseString = null;
820         List<ResponseDocument> responseDocumentList = response.getDocuments();
821         for (ResponseDocument responseDocument : responseDocumentList) {
822             Content contentObj = responseDocument.getContent();
823             responseString = contentObj.getContent();
824         }
825         return responseString;
826     }
827 
828     /**
829      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
830      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
831      *
832      * @param instanceIdsList
833      * @return List<WorkBibDocument>
834      */
835 //    public List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
836 //        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
837 //        for (String instanceId : instanceIdsList) {
838 //            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
839 //            instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
840 //            instanceIdMapList.add(instanceIdMap);
841 //        }
842 //
843 //        QueryService queryService = QueryServiceImpl.getInstance();
844 //        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
845 //        try {
846 //            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
847 //        } catch (Exception ex) {
848 //            // TODO Auto-generated catch block
849 //            ex.printStackTrace();
850 //        }
851 //        return workBibDocuments;
852 //    }
853 
854     /**
855      * This method takes locationLevelCode and locationLevelName as parameters and split level name and returns as location level.
856      *
857      * @param locationLevel
858      * @param locationLevelCode
859      * @param locationLevelName
860      * @return
861      */
862     public org.kuali.ole.docstore.common.document.content.instance.LocationLevel setLocationLevels(org.kuali.ole.docstore.common.document.content.instance.LocationLevel locationLevel, String locationLevelCode,
863                                            String locationLevelName) {
864 
865         String[] levelNames = locationLevelName.split("/");
866         String[] levels = locationLevelCode.split("/");
867         locationLevel.setName(levelNames[0]);
868         locationLevel.setLevel(levels[0]);
869         String levlName = "";
870         String levl = "";
871         if (locationLevelName.contains("/") && locationLevelCode.contains("/")) {
872             levlName = locationLevelName.replace(levelNames[0] + "/", "");
873             levl = locationLevelCode.replace(levels[0] + "/", "");
874         } else {
875             levlName = locationLevelName.replace(levelNames[0], "");
876             levl = locationLevelCode.replace(levels[0], "");
877         }
878         if ((levlName != null && !levlName.equals("")) && (levl != null && !levl.equals(""))) {
879             org.kuali.ole.docstore.common.document.content.instance.LocationLevel newLocationLevel = new org.kuali.ole.docstore.common.document.content.instance.LocationLevel();
880             locationLevel.setLocationLevel(setLocationLevels(newLocationLevel, levl, levlName));
881         }
882         return locationLevel;
883     }
884 
885     public Response createItemToDocstore(String instanceUuid, org.kuali.ole.docstore.common.document.content.instance.Item item) {
886         String oleItemXMLString = new ItemOlemlRecordProcessor().toXML(item);
887         Response responseObject = null;
888         try {
889             String response = createItemForInstanceRecord(instanceUuid, OLEConstants.ITEM_DOC_TYPE, oleItemXMLString);
890             responseObject = new ResponseHandler().toObject(response);
891         } catch (Exception ex) {
892             // TODO Auto-generated catch block
893             ex.printStackTrace();
894         }
895         return responseObject;
896     }
897 
898     public String updateOleHoldingToDocstore(OleHoldings oleHoldings) throws Exception {
899         String oleHoldingXMLString = new HoldingOlemlRecordProcessor().toXML(oleHoldings);
900         String oleHoldingUUID = oleHoldings.getHoldingsIdentifier();
901 
902         String response = updateInstanceRecord(oleHoldingUUID, OLEConstants.HOLDING_DOC_TYPE, oleHoldingXMLString);
903         return response;
904     }
905 
906     public String updateOleItemToDocstore(Item item) throws Exception {
907         String oleItemXMLString = new ItemOlemlRecordProcessor().toXML(item);
908         // String itemXMLString = new UpdateDocstoreRecord().getResponseFromWorkItem(item);
909         String oleItemUUID = item.getItemIdentifier();
910         if (LOG.isDebugEnabled()) {
911             LOG.debug("oleItemUUID---------->" + oleItemUUID);
912         }
913         String response = updateInstanceRecord(oleItemUUID, OLEConstants.ITEM_DOC_TYPE, oleItemXMLString);
914         return response;
915     }
916 
917     private WorkItemOlemlRecordProcessor getWorkItemOlemlRecordProcessor() {
918         if (workItemOlemlRecordProcessor == null) {
919             workItemOlemlRecordProcessor = new WorkItemOlemlRecordProcessor();
920         }
921         return workItemOlemlRecordProcessor;
922     }
923 
924     public WorkHoldingOlemlRecordProcessor getWorkHoldingOlemlRecordProcessor() {
925         if (workHoldingOlemlRecordProcessor == null) {
926             workHoldingOlemlRecordProcessor = new WorkHoldingOlemlRecordProcessor();
927         }
928         return workHoldingOlemlRecordProcessor;
929     }
930 
931     public String updateInstanceRecord(String uuid, String docType, String xmlContent) throws Exception {
932         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
933         Request requestObject = new Request();
934         requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
935                 .getPrincipalId() : "");
936         requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
937         RequestDocument requestDocument = new RequestDocument();
938 
939         requestDocument.setId(uuid);
940         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
941         requestDocument.setType(docType); // docType should be either holdings or item
942         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
943         requestDocument.setContent(new Content(xmlContent));
944 
945         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
946         requestDocuments.add(requestDocument);
947         requestObject.setRequestDocuments(requestDocuments);
948 
949         RequestHandler requestHandler = new RequestHandler();
950         String xml = requestHandler.toXML(requestObject);
951 
952         String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xml, "UTF-8");
953 
954         return postData(docstoreURL, queryString);
955     }
956 
957     public static String postData(String target, String content) throws Exception {
958         String response = "";
959         URL url = new URL(target);
960         URLConnection conn = url.openConnection();
961         conn.setDoInput(true);
962         conn.setDoOutput(true);
963         conn.setUseCaches(false);
964         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
965 
966         Writer w = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
967         w.write(content);
968         w.close();
969         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
970         String temp;
971         while ((temp = in.readLine()) != null) {
972             response += temp + "\n";
973         }
974         in.close();
975         return response;
976     }
977 
978     /**
979      * Method to add NEW ITEM for existing Instance record
980      *
981      * @param instanceUuid
982      * @param docType
983      * @param xmlContent
984      * @return Docstore XML response with success/failure status
985      * @throws Exception
986      */
987     public String createItemForInstanceRecord(String instanceUuid, String docType, String xmlContent) throws Exception {
988         String docstoreURL = ConfigContext.getCurrentContextConfig().getProperty(DOCSTORE_URL);
989         Request requestObject = new Request();
990         requestObject.setUser(GlobalVariables.getUserSession() != null ? GlobalVariables.getUserSession()
991                 .getPrincipalId() : "");
992         requestObject.setOperation(OLEConstants.CHECK_IN_OPERATION);
993         RequestDocument requestDocument = new RequestDocument();
994 
995         requestDocument.setId(instanceUuid);
996         requestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
997         requestDocument.setType(OLEConstants.BIB_TYPE_INSTANCE);
998         requestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
999 
1000 
1001         RequestDocument linkedRequestDocument = new RequestDocument();
1002         linkedRequestDocument.setId(OLEConstants.NEW_ITEM_ID);
1003         linkedRequestDocument.setCategory(OLEConstants.BIB_CATEGORY_WORK);
1004         linkedRequestDocument.setType(docType);
1005         linkedRequestDocument.setFormat(OLEConstants.BIB_FORMAT_OLEML);
1006         linkedRequestDocument.setContent(new Content(xmlContent));
1007 
1008         List<RequestDocument> linkedRequestDocuments = new ArrayList<RequestDocument>();
1009         linkedRequestDocuments.add(linkedRequestDocument);
1010         requestDocument.setLinkedRequestDocuments(linkedRequestDocuments);
1011 
1012 
1013         ArrayList<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
1014         requestDocuments.add(requestDocument);
1015         requestObject.setRequestDocuments(requestDocuments);
1016 
1017         RequestHandler requestHandler = new RequestHandler();
1018         String xml = requestHandler.toXML(requestObject);
1019 
1020         String queryString = UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING + URLEncoder.encode(xml, "UTF-8");
1021 
1022         return postData(docstoreURL, queryString);
1023 
1024     }
1025 
1026 
1027     public String getItemLocations(String location) {
1028         String[] locations = location.split("/");
1029         StringBuffer locationString = new StringBuffer();
1030         for (int i = locations.length - 1; i >= 1; i--) {
1031             if (i == 1) {
1032                 locationString = locationString.append(locations[i]);
1033             } else {
1034                 locationString = locationString.append(locations[i] + "/");
1035             }
1036         }
1037         return locationString.toString();
1038     }
1039 
1040 
1041 
1042     @Override
1043     public void createOrUpdateDocStoreBasedOnLocation(PurchaseOrderDocument document, PurApItem item, String currentDocumentTypeName, String note) {
1044         OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) item;
1045         try {
1046             List<String> itemTitleIdsList = new ArrayList<String>();
1047             List<BibTree> bibTrees= new ArrayList<BibTree>();
1048             itemTitleIdsList.add(olePurchaseOrderItem.getItemTitleId());
1049             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1050             for (BibTree bibTree : bibTrees) {
1051                 if (null != olePurchaseOrderItem.getItemTitleId()) {
1052                     performDocstoreUpdateForRequisitionAndPOItem(document, olePurchaseOrderItem,
1053                             bibTree, currentDocumentTypeName, note);
1054                 }
1055             }
1056         } catch (Exception e) {
1057             e.printStackTrace();
1058             throw new RuntimeException(e);
1059         }
1060     }
1061     private List<BibTree> getBibTreeDocuments(List<String> instanceIdsList) {
1062         List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
1063         for (String instanceId : instanceIdsList) {
1064             LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
1065             instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
1066             instanceIdMapList.add(instanceIdMap);
1067         }
1068         List<BibTree> bibTrees = new ArrayList<BibTree>();
1069         try {
1070             bibTrees = getWorkBibRecords(instanceIdMapList);
1071         } catch (Exception ex) {
1072             // TODO Auto-generated catch block
1073             ex.printStackTrace();
1074         }
1075         return bibTrees;
1076     }
1077     public List<BibTree> getWorkBibRecords(List<LinkedHashMap<String, String>> uuidsMapList) throws Exception {
1078         List<BibTree> bibTres = new ArrayList<BibTree>();
1079         BibTree bibTree=new BibTree();
1080         for (LinkedHashMap<String, String> uuidsMap : uuidsMapList) {
1081             if (uuidsMap.containsKey(DocType.BIB.getDescription())) {
1082                 String bibId = uuidsMap.get(DocType.BIB.getDescription());
1083                 if (LOG.isDebugEnabled()) {
1084                     LOG.debug(" bibId ---------------> " + bibId);
1085                 }
1086                 if (StringUtils.isNotBlank(bibId)) {
1087                     bibTree=getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(bibId.toString());
1088                 }
1089             }
1090             bibTres.add(bibTree);
1091         }
1092         return bibTres;
1093     }
1094     /**
1095      * Populate location levels.
1096      *
1097      * @throws Exception
1098      */
1099     public String getLocationLevelCode( OleCopy copy) throws Exception {
1100         LOG.debug("Inside the getLocationLevelCode method");
1101         StringBuffer location = new StringBuffer();
1102         StringBuffer locationLevelCode = new StringBuffer();
1103         String[] locationCopiesSplit = copy.getLocation().split("/");
1104         for(String locationCode : locationCopiesSplit){
1105             OleLocation oleLocation =getLocationByLocationCode(locationCode);
1106             if(oleLocation!=null){
1107                 OleLocationLevel oleLocationLevel =  oleLocation.getOleLocationLevel();
1108                 String levelCode = oleLocationLevel!=null && oleLocationLevel.getLevelCode()!=null ? oleLocationLevel.getLevelCode() : "" ;
1109                 setLocation(locationLevelCode,location,levelCode,oleLocation.getLocationCode(),oleLocation.getLocationName());
1110             }
1111         }
1112         return locationLevelCode.toString();
1113     }
1114 
1115     /**
1116      * sets the value for location levels in Loan Document.
1117      *
1118      * @param levelCode
1119      * @param locationCode
1120      * @throws Exception
1121      */
1122     private void setLocation(StringBuffer locationLevelCode,StringBuffer location, String levelCode, String locationCode, String locationName) throws Exception {
1123         LOG.debug("Inside the setLocation method");
1124         if (locationCode != null) {
1125             if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_SHELVING)) {
1126                 location.append(locationName);
1127                 locationLevelCode.append(levelCode);
1128             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_COLLECTION)) {
1129                 location.append(locationName + "/");
1130                 locationLevelCode.append(levelCode + "/");
1131             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_LIBRARY)) {
1132                 location.append(locationName + "/");
1133                 locationLevelCode.append(levelCode + "/");
1134             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_INSTITUTION)) {
1135                 location.append(locationName + "/");
1136                 locationLevelCode.append(levelCode + "/");
1137             } else if (levelCode.equalsIgnoreCase(org.kuali.ole.OLEConstants.OLEBatchProcess.LOCATION_LEVEL_CAMPUS)) {
1138                 location.append(locationName + "/");
1139                 locationLevelCode.append(levelCode + "/");
1140             }
1141         }
1142     }
1143 
1144     /**
1145      * This method returns location using location code.
1146      *
1147      * @param locationCode
1148      * @return
1149      * @throws Exception
1150      */
1151     private OleLocation getLocationByLocationCode(String locationCode) throws Exception {
1152         LOG.debug("Inside the getLocationByLocationCode method");
1153         Map barMap = new HashMap();
1154         barMap.put(org.kuali.ole.OLEConstants.LOC_CD, locationCode);
1155         List<OleLocation> matchingLocation = (List<OleLocation>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLocation.class, barMap);
1156         return matchingLocation.size()>0 ? matchingLocation.get(0) : null;
1157     }
1158 
1159 
1160     /*@Override
1161     public void updateItemNote(PurApItem item, String note) {
1162         OleRequisitionItem oleRequisitionItem = (OleRequisitionItem) item;
1163         try {
1164             List<String> itemTitleIdsList = new ArrayList<String>();
1165             List<BibTree> bibTrees = new ArrayList<BibTree>();
1166             itemTitleIdsList.add(oleRequisitionItem.getItemTitleId());
1167             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1168             for (BibTree bibTree : bibTrees) {
1169                 if (null != oleRequisitionItem.getItemTitleId()) {
1170                     performDocstoreUpdateForRequisitionItemRecord(oleRequisitionItem,
1171                             bibTree, note);
1172                 }
1173             }
1174         } catch (Exception e) {
1175             e.printStackTrace();
1176             throw new RuntimeException(e);
1177         }
1178     }
1179 
1180     private void performDocstoreUpdateForRequisitionItemRecord(OleRequisitionItem oleRequisitionItem , BibTree bibTree, String note) throws Exception {
1181         List<OleCopy> copyList = oleRequisitionItem.getCopyList();
1182         String itemTitleId = oleRequisitionItem.getItemTitleId();
1183         OleCopyHelperService oleCopyHelperService =  new OleCopyHelperServiceImpl();
1184         HashMap<String, List<OleCopy>> copyListBasedOnLocation = oleCopyHelperService.getCopyListBasedOnLocation(copyList, itemTitleId);
1185         Iterator<Map.Entry<String, List<OleCopy>>> entries = copyListBasedOnLocation.entrySet().iterator();
1186         int count = 0;
1187         if (copyList.size() == 0) {
1188             OleCopy oleCopy = new OleCopy();
1189             oleCopy.setLocation(oleRequisitionItem.getItemLocation());
1190             if (bibTree.getHoldingsTrees().size() == 1) {
1191                 updateOleHoldingStaffOnly(bibTree,oleCopy,true);
1192                 bibTree.getBib().setStaffOnly(true);
1193                 getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1194             }
1195             for (int items=0; items < bibTree.getHoldingsTrees().size(); items++) {
1196                 updateOleItemStaffOnly(bibTree.getHoldingsTrees().get(items).getItems().get(0).getId(),null,note,true);
1197                 oleCopy.setReqDocNum(null);
1198                 oleCopy.setReqItemId(null);
1199             }
1200         }
1201         while (entries.hasNext()) {
1202             Map.Entry<String, List<OleCopy>> entry = entries.next();
1203             List<OleCopy> oleCopyList = entry.getValue();
1204             count++;
1205             if (oleCopyList != null && oleCopyList.size() > 0) {
1206                 if (bibTree.getHoldingsTrees().size() == 1) {
1207                     OleCopy copy = oleCopyList.get(0);
1208                     updateOleHoldingStaffOnly(bibTree,copy,true);
1209                     bibTree.getBib().setStaffOnly(true);
1210                     getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1211                 }
1212                 for (OleCopy oleCopy : copyList) {
1213                     for (int items=0; items < bibTree.getHoldingsTrees().size(); items++) {
1214                         for (int singleItem=0; singleItem < bibTree.getHoldingsTrees().get(items).getItems().size(); singleItem++) {
1215                             if (oleCopy.getItemUUID().equalsIgnoreCase(bibTree.getHoldingsTrees().get(items).getItems().get(singleItem).getId())) {
1216                                 if (!bibTree.getHoldingsTrees().get(items).getItems().get(singleItem).isStaffOnly()) {
1217                                     updateOleItemStaffOnly(oleCopy.getItemUUID(),null,note,true);
1218                                     oleCopy.setReqDocNum(null);
1219                                     oleCopy.setReqItemId(null);
1220                                 }
1221                             }
1222 
1223                         }
1224                     }
1225                 }
1226             }
1227         }
1228 
1229     }*/
1230 
1231     private List<DonorInfo> setDonorInfoToItem(List<OLELinkPurapDonor> oleDonors,List<DonorInfo> donorInfoList){
1232         for (OLELinkPurapDonor oleLinkPurapDonor : oleDonors) {
1233             DonorInfo donorInfo = new DonorInfo();
1234             donorInfo.setDonorCode(oleLinkPurapDonor.getDonorCode());
1235             Map donorMap = new HashMap();
1236             donorMap.put(OLEConstants.DONOR_CODE, oleLinkPurapDonor.getDonorCode());
1237             OLEDonor oleDonor = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OLEDonor.class, donorMap);
1238             if (oleDonor != null) {
1239                 if (StringUtils.isNotEmpty(oleDonor.getDonorNote()))
1240                     donorInfo.setDonorNote(oleDonor.getDonorNote());
1241                 if (StringUtils.isNotEmpty(oleDonor.getDonorPublicDisplay()))
1242                     donorInfo.setDonorPublicDisplay(oleDonor.getDonorPublicDisplay());
1243             }
1244             donorInfoList.add(donorInfo);
1245         }
1246         return donorInfoList;
1247     }
1248 
1249     @Override
1250     public void updateItemLocation(PurchaseOrderDocument document, PurApItem item) {
1251         OlePurchaseOrderItem olePurchaseOrderItem = (OlePurchaseOrderItem) item;
1252         try {
1253             List<String> itemTitleIdsList = new ArrayList<String>();
1254             List<BibTree> bibTrees= new ArrayList<BibTree>();
1255             String poLineItemId =  olePurchaseOrderItem.getItemIdentifier()!=null?olePurchaseOrderItem.getItemIdentifier().toString():null;
1256             itemTitleIdsList.add(olePurchaseOrderItem.getItemTitleId());
1257             bibTrees = getBibTreeDocuments(itemTitleIdsList);
1258             for (BibTree bibTree : bibTrees) {
1259                 if (null != olePurchaseOrderItem.getItemTitleId()) {
1260                     if (olePurchaseOrderItem.isItemLocationChangeFlag()) {
1261                         if (StringUtils.isNotBlank(olePurchaseOrderItem.getItemLocation()) && olePurchaseOrderItem.getCopyList().size() == 1) {
1262                             if( bibTree.getHoldingsTrees().size()>0 ){
1263                                 OleCopy copy = olePurchaseOrderItem.getCopyList().get(0);
1264                                 copy.setLocation(olePurchaseOrderItem.getItemLocation());
1265                                 updateOleHolding(copy.getInstanceId(),bibTree, copy);
1266                                 updateOleItem(document.getPurapDocumentIdentifier().toString(), olePurchaseOrderItem.getCopyList().get(0).getItemUUID(),poLineItemId, olePurchaseOrderItem);
1267                             }
1268                         }
1269                     }
1270                 }
1271             }
1272         } catch (Exception e) {
1273             e.printStackTrace();
1274             throw new RuntimeException(e);
1275         }
1276     }
1277 
1278     private void updateOleHoldingStaffOnly(String holdingId, BibTree bibTree, OleCopy copy,boolean staffOnly) throws Exception {
1279         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1280         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1281         oleHoldings.setHoldingsIdentifier(holdingId);
1282         Holdings newHoldings=new PHoldings();
1283         newHoldings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1284         newHoldings.setStaffOnly(staffOnly);
1285         newHoldings.setId(holdingId);
1286         newHoldings.setBib(bibTree.getBib());
1287         getDocstoreClientLocator().getDocstoreClient().updateHoldings(newHoldings);
1288     }
1289 
1290     private void updateOleHolding(String holdingId, BibTree bibTree, OleCopy copy) throws Exception {
1291         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1292         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1293         oleHoldings.setHoldingsIdentifier(holdingId);
1294         Holdings holdings=new PHoldings();
1295         holdings.setId(holdingId);
1296         holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1297         holdings.setBib(bibTree.getBib());
1298         getDocstoreClientLocator().getDocstoreClient().updateHoldings(holdings);
1299     }
1300 
1301     private void updateOleItem(String poNumber, String itemId, String poLineItemId, OlePurchaseOrderItem singleItem) throws Exception {
1302         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemId);
1303         Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
1304         List<DonorInfo> donorInfoList = setDonorInfoToItem(singleItem.getOleDonors(), new ArrayList<DonorInfo>());
1305         itemContent.setDonorInfo(donorInfoList);
1306         itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
1307         if (singleItem != null) {
1308             itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1309             if (singleItem.getExtendedPrice() != null) {
1310                 itemContent.setPrice(singleItem.getExtendedPrice().toString());
1311             }
1312             itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1313         }
1314         itemContent.setItemIdentifier(itemId);
1315         item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
1316         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
1317     }
1318 
1319     private void updateOleItemStaffOnly(String poNumber, String itemId, String poLineItemId, String note, boolean staffOnly, OlePurchaseOrderItem singleItem) throws Exception {
1320         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemId);
1321         Item itemContent=new ItemOlemlRecordProcessor().fromXML(item.getContent());
1322         if (StringUtils.isNotEmpty(poNumber)) {
1323             itemContent.setPurchaseOrderLineItemIdentifier(poNumber);
1324         }
1325         if (singleItem != null) {
1326             itemContent.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1327             if (singleItem.getExtendedPrice() != null) {
1328                 itemContent.setPrice(singleItem.getExtendedPrice().toString());
1329             }
1330             itemContent.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1331         }
1332         itemContent.setItemIdentifier(itemId);
1333         if (StringUtils.isNotEmpty(note)) {
1334             List<Note> noteList = itemContent.getNote()!=null ? itemContent.getNote() : (List<Note>) new ArrayList<Note>();
1335             Note noteObj = new Note();
1336             noteObj.setType(OLEConstants.NON_PUBLIC);
1337             noteObj.setValue(note);
1338             noteList.add(noteObj);
1339             itemContent.setNote(noteList);
1340         }
1341         item.setContent(new ItemOlemlRecordProcessor().toXML(itemContent));
1342         item.setStaffOnly(staffOnly);
1343         item.setId(itemContent.getItemIdentifier());
1344         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
1345     }
1346 
1347     private void updateRecordForPOVoidDocument(String poNumber, BibTree bibTree, String poLineItemId, String note ,List<OleCopy> copyList, OlePurchaseOrderItem singleItem) throws Exception {
1348         OleCopy copy = copyList.get(0);
1349         if (bibTree.getHoldingsTrees().size() == 1 && copyList.size()==1) {
1350             bibTree.getBib().setStaffOnly(true);
1351             getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1352         }
1353         if (copyList.size()==1) {
1354             updateOleHoldingStaffOnly(copy.getInstanceId(),bibTree,copy,true);
1355         }
1356         for (OleCopy oleCopy : copyList) {
1357             updateOleItemStaffOnly(poNumber, oleCopy.getItemUUID(),poLineItemId,note,true, singleItem);
1358             oleCopy.setReqDocNum(null);
1359             oleCopy.setReqItemId(null);
1360         }
1361     }
1362 
1363     private void updateRecordForPOReOpenDocument(String poNumber, BibTree bibTree, String poLineItemId, List<OleCopy> copyList, OlePurchaseOrderItem singleItem) throws Exception {
1364         OleCopy copy = copyList.get(0);
1365         if (bibTree.getBib().getId().equalsIgnoreCase(OLEConstants.TRUE)) {
1366             bibTree.getBib().setStaffOnly(false);
1367             getDocstoreClientLocator().getDocstoreClient().updateBib(bibTree.getBib());
1368         }
1369         if (copyList.size()==1) {
1370             updateOleHoldingStaffOnly(copy.getInstanceId(),bibTree,copy,false);
1371         }
1372         for (OleCopy oleCopy : copyList) {
1373             updateOleItemStaffOnly(poNumber, oleCopy.getItemUUID(),poLineItemId,null,false, singleItem);
1374             oleCopy.setReqDocNum(null);
1375             oleCopy.setReqItemId(null);
1376         }
1377     }
1378 
1379     private void updateRecordForPOAmendmentDocument(String poNumber, BibTree bibTree,List<OleCopy> copyList, String poLineItemId,List<OLELinkPurapDonor> oleDonors,List<OleCopy> oleCopyList,
1380                                                     String itemTypeDescription,String itemStatusValue, OlePurchaseOrderItem singleItem) throws Exception {
1381         OleCopy copy = oleCopyList.get(0);
1382         if (copyList.size()>1) {
1383             if (!this.copyFlag) {
1384                 List <OleCopy> newCopyList = new ArrayList<>();
1385                 int j=0;
1386                 for (OleCopy newCopy : oleCopyList) {
1387                     if (!this.newCopyFlag) { // existing record's location  is updated with First copy from copyList
1388                         updateOleHolding(bibTree.getHoldingsTrees().get(0).getHoldings().getId(),bibTree, newCopy);
1389                         if (bibTree.getHoldingsTrees().get(0).getItems().size()==1) {
1390                             updateOleItem(poNumber, bibTree.getHoldingsTrees().get(0).getItems().get(0).getId(),poLineItemId, singleItem);
1391                             newCopy.setInstanceId(bibTree.getHoldingsTrees().get(0).getHoldings().getId());
1392                             newCopy.setItemUUID(bibTree.getHoldingsTrees().get(0).getItems().get(0).getId());
1393                             for (int copyCnt=0; copyCnt<oleCopyList.size(); copyCnt++) {
1394                                 if (!newCopy.getCopyId().equals(oleCopyList.get(copyCnt).getCopyId())) {
1395                                     newCopyList.add(oleCopyList.get(copyCnt));
1396                                 }
1397                             }
1398                             this.copyCount++;
1399                         }
1400                         else {
1401                             int itemRecord=0;
1402                             for (int copyRecord=0;copyRecord<oleCopyList.size();) {
1403                                 if ( itemRecord<bibTree.getHoldingsTrees().get(0).getItems().size()) {
1404                                     updateOleItem(poNumber, bibTree.getHoldingsTrees().get(0).getItems().get(itemRecord).getId(), poLineItemId, singleItem);
1405                                     oleCopyList.get(copyRecord).setInstanceId(bibTree.getHoldingsTrees().get(0).getHoldings().getId());
1406                                     oleCopyList.get(copyRecord).setItemUUID(bibTree.getHoldingsTrees().get(0).getItems().get(itemRecord).getId());
1407                                     this.copyCount++;itemRecord++;copyRecord++;
1408                                 }
1409                                 if(itemRecord==bibTree.getHoldingsTrees().get(0).getItems().size()){
1410                                     if (copyRecord < oleCopyList.size()) {
1411                                         newCopyList.add(oleCopyList.get(copyRecord));
1412                                         copyRecord++;
1413                                     }
1414                                 }
1415                             }
1416                         }
1417                         this.newCopyFlag = true;
1418                     } else {
1419                         if (newCopyList.size()>0) {
1420 
1421                             /*List<OleCopy> newCopies = new ArrayList();
1422                             for (int oleCopy=0; oleCopy<newCopyList.size();) {
1423                                 newCopies.add(newCopyList.get(oleCopy));
1424                                 createOleHoldingsTree(bibTree,copyList,poLineItemId,oleDonors,newCopies,itemTypeDescription,itemStatusValue);
1425                                 newCopies.clear();
1426                                 oleCopy++;
1427                             }*/
1428                             createOleHoldingsTree(poNumber, bibTree,newCopyList,poLineItemId,oleDonors,oleCopyList,itemTypeDescription,itemStatusValue,singleItem);
1429                         }
1430                         if (this.copyCount==oleCopyList.size()) {
1431                             break;
1432                         }
1433                     }
1434                 }
1435                 this.copyFlag = true;
1436             } else {  // new record's are created with its respective locations.
1437                 createOleHoldingsTree(poNumber, bibTree,copyList,poLineItemId,oleDonors,oleCopyList,itemTypeDescription,itemStatusValue, singleItem);
1438             }
1439         }
1440     }
1441 
1442     public void createOleHoldingsTree(String poNumber, BibTree bibTree,List<OleCopy> copyList, String poLineItemId,List<OLELinkPurapDonor> oleDonors,List<OleCopy> oleCopyList,
1443                                         String itemTypeDescription,String itemStatusValue, OlePurchaseOrderItem singleItem) throws Exception {
1444         OleCopy copy = oleCopyList.get(0);
1445         Holdings pHoldings = new PHoldings();
1446         if (StringUtils.isNotBlank(copy.getInstanceId())) {
1447             pHoldings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(copy.getInstanceId());
1448         }
1449         List<org.kuali.ole.docstore.common.document.Item> itemList = new ArrayList<org.kuali.ole.docstore.common.document.Item>();
1450         org.kuali.ole.docstore.common.document.content.instance.OleHoldings oleHoldings = setHoldingDetails(copy);
1451         oleHoldings.setHoldingsIdentifier(null);
1452         oleHoldings.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
1453         List<Integer> copyIdList = new ArrayList<>();
1454         for (OleCopy oleCopy : copyList) {
1455             if (oleCopy.getLocation().equals(copy.getLocation())) {
1456                 Item item = setItemDetails(oleCopy, itemTypeDescription);
1457                 ItemStatus itemStatus = new ItemStatus();
1458                 itemStatus.setCodeValue(itemStatusValue);
1459                 itemStatus.setFullValue(itemStatusValue);
1460                 item.setItemStatus(itemStatus);
1461                 item.setPurchaseOrderLineItemIdentifier(poNumber);
1462                 if (singleItem != null) {
1463                     item.setVendorLineItemIdentifier(singleItem.getVendorItemPoNumber());
1464                     if (singleItem.getExtendedPrice() != null) {
1465                         item.setPrice(singleItem.getExtendedPrice().toString());
1466                     }
1467                     item.setFund(populateFundCodes(singleItem.getSourceAccountingLines()));
1468                 }
1469                 List<DonorInfo> donorInfoList = setDonorInfoToItem(oleDonors, new ArrayList<DonorInfo>());
1470                 item.setDonorInfo(donorInfoList);
1471                 org.kuali.ole.docstore.common.document.Item itemDocument = new org.kuali.ole.docstore.common.document.Item();
1472                 itemDocument.setContent(new ItemOlemlRecordProcessor().toXML(item));
1473                 itemDocument.setCategory(OLEConstants.ITEM_CATEGORY);
1474                 itemDocument.setType(OLEConstants.ITEM_TYPE);
1475                 itemDocument.setFormat(OLEConstants.ITEM_FORMAT);
1476                 if (StringUtils.isNotBlank(copy.getInstanceId())) {
1477                     itemDocument.setHolding(pHoldings);
1478                     getDocstoreClientLocator().getDocstoreClient().createItem(itemDocument);
1479                 } else {
1480                     itemList.add(itemDocument);
1481                 }
1482                 copyIdList.add(oleCopy.getCopyId());
1483             }
1484         }
1485         HoldingsTree holdingsTree = new HoldingsTree();
1486         if (StringUtils.isBlank(copy.getInstanceId())) {
1487             holdingsTree.getItems().addAll(itemList);
1488             Holdings holdings = new PHoldings();
1489             holdings.setCategory(DocCategory.WORK.getCode());
1490             holdings.setType(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode());
1491             holdings.setFormat(org.kuali.ole.docstore.common.document.content.enums.DocFormat.OLEML.getCode());
1492             holdings.setContent(new HoldingOlemlRecordProcessor().toXML(oleHoldings));
1493             Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(bibTree.getBib().getId());
1494             holdings.setBib(bib);
1495             holdingsTree.setHoldings(holdings);
1496             getDocstoreClientLocator().getDocstoreClient().createHoldingsTree(holdingsTree);
1497         } else {
1498             holdingsTree = getDocstoreClientLocator().getDocstoreClient().retrieveHoldingsTree(copy.getInstanceId());
1499         }
1500         int i = 0;
1501         for (org.kuali.ole.docstore.common.document.Item item : holdingsTree.getItems()) {
1502             for (OleCopy oleCopy : copyList) {
1503                 if (copyIdList != null && copyIdList.size() > i && copyIdList.get(i).equals(oleCopy.getCopyId())) {
1504                     oleCopy.setInstanceId(holdingsTree.getHoldings().getId());
1505                     oleCopy.setItemUUID(item.getId());
1506                     this.copyCount++;
1507                     if (LOG.isDebugEnabled()) {
1508                         LOG.debug("Instance UUID" + holdingsTree.getHoldings().getId() + "****** Item UUID" + item.getId());
1509                     }
1510                 }
1511             }
1512             i++;
1513 
1514         }
1515     }
1516 
1517     private String populateFundCodes(List<PurApAccountingLine> purApAccountingLines) {
1518         StringBuffer fundCode = new StringBuffer();
1519         List fundCodeList = new ArrayList();
1520         if (purApAccountingLines != null && purApAccountingLines.size() > 0) {
1521             for (PurApAccountingLine accountingLine : purApAccountingLines) {
1522                 Map map = new HashMap();
1523                 map.put(org.kuali.ole.OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
1524                 map.put(org.kuali.ole.OLEConstants.OBJECT_CODE, accountingLine.getFinancialObjectCode());
1525                 OleVendorAccountInfo oleVendorAccountInfo = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleVendorAccountInfo.class, map);
1526                 if (oleVendorAccountInfo != null && !fundCodeList.contains(oleVendorAccountInfo.getVendorRefNumber())) {
1527                     fundCodeList.add(oleVendorAccountInfo.getVendorRefNumber());
1528                     fundCode.append(oleVendorAccountInfo.getVendorRefNumber());
1529                     fundCode.append(org.kuali.ole.OLEConstants.COMMA);
1530                     fundCode.append(' ');
1531                 }
1532             }
1533         }
1534         if (fundCode.length() > 0) {
1535             fundCode.deleteCharAt(fundCode.length() - 2);
1536             return fundCode.toString();
1537         }
1538         return null;
1539     }
1540 
1541     public boolean isValidLocation(String location) {
1542         List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
1543         if (locationList != null && locationList.size() > 0) {
1544             for (String locationValue : locationList) {
1545                 if (locationValue.equalsIgnoreCase(location)) {
1546                     return true;
1547                 }
1548             }
1549         }
1550         return false;
1551     }
1552 
1553 }