View Javadoc
1   package org.kuali.ole.service.impl;
2   
3   import org.apache.commons.io.FileUtils;
4   import org.apache.commons.lang3.StringUtils;
5   import org.apache.log4j.Logger;
6   import org.apache.commons.collections.CollectionUtils;
7   import org.joda.time.DateTime;
8   import org.kuali.ole.OLEConstants;
9   import org.kuali.ole.coa.businessobject.*;
10  import org.kuali.ole.describe.form.WorkEInstanceOlemlForm;
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.instance.*;
15  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
16  import org.kuali.ole.docstore.common.document.ids.BibId;
17  import org.kuali.ole.docstore.common.document.ids.HoldingsId;
18  import org.kuali.ole.docstore.common.search.SearchParams;
19  import org.kuali.ole.docstore.common.search.SearchResponse;
20  import org.kuali.ole.docstore.common.search.SearchResult;
21  import org.kuali.ole.docstore.common.search.SearchResultField;
22  import org.kuali.ole.module.purap.PurapConstants;
23  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
24  import org.kuali.ole.module.purap.businessobject.PurchaseOrderType;
25  import org.kuali.ole.module.purap.businessobject.RequisitionAccount;
26  import org.kuali.ole.module.purap.businessobject.RequisitionItem;
27  import org.kuali.ole.module.purap.document.RequisitionDocument;
28  import org.kuali.ole.module.purap.document.service.OlePurapService;
29  import org.kuali.ole.pojo.OleBibRecord;
30  import org.kuali.ole.select.OleSelectConstant;
31  import org.kuali.ole.select.bo.*;
32  import org.kuali.ole.select.businessobject.*;
33  import org.kuali.ole.select.document.*;
34  import org.kuali.ole.select.bo.OLECreatePO;
35  import org.kuali.ole.select.form.OLEEResourceRecordForm;
36  import org.kuali.ole.select.gokb.*;
37  import org.kuali.ole.select.service.OLESelectDaoOjb;
38  import org.kuali.ole.select.service.OleReqPOCreateDocumentService;
39  import org.kuali.ole.service.OLEEResourceSearchService;
40  import org.kuali.ole.sys.businessobject.Building;
41  import org.kuali.ole.sys.businessobject.FinancialSystemDocumentHeader;
42  import org.kuali.ole.sys.businessobject.Room;
43  import org.kuali.ole.sys.context.SpringContext;
44  import org.kuali.ole.sys.document.FinancialSystemMaintenanceDocument;
45  import org.kuali.ole.sys.service.UniversityDateService;
46  import org.kuali.ole.vnd.VendorConstants;
47  import org.kuali.ole.vnd.businessobject.*;
48  import org.kuali.ole.vnd.document.service.VendorService;
49  import org.kuali.rice.core.api.config.property.ConfigContext;
50  import org.kuali.rice.core.api.config.property.ConfigurationService;
51  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
52  import org.kuali.rice.core.api.util.RiceKeyConstants;
53  import org.kuali.rice.core.api.util.RiceConstants;
54  import org.kuali.rice.core.api.util.type.KualiDecimal;
55  import org.kuali.rice.core.api.util.type.KualiInteger;
56  import org.kuali.rice.coreservice.api.CoreServiceApiServiceLocator;
57  import org.kuali.rice.coreservice.api.parameter.Parameter;
58  import org.kuali.rice.coreservice.api.parameter.ParameterKey;
59  import org.kuali.rice.coreservice.impl.parameter.ParameterBo;
60  import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
61  import org.kuali.rice.kew.api.document.search.DocumentSearchResult;
62  import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
63  import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
64  import org.kuali.rice.kew.service.KEWServiceLocator;
65  import org.kuali.rice.krad.bo.DocumentHeader;
66  import org.kuali.rice.krad.service.BusinessObjectService;
67  import org.kuali.rice.krad.service.DocumentHeaderService;
68  import org.kuali.rice.krad.service.KRADServiceLocator;
69  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
70  import org.kuali.rice.krad.util.GlobalVariables;
71  import org.kuali.rice.krad.util.KRADConstants;
72  import org.kuali.rice.krad.util.ObjectUtils;
73  import org.springframework.util.FileCopyUtils;
74  import org.springframework.web.multipart.MultipartFile;
75  
76  import javax.servlet.http.HttpServletResponse;
77  import java.io.*;
78  import java.math.BigDecimal;
79  import java.math.RoundingMode;
80  import java.sql.*;
81  import java.text.SimpleDateFormat;
82  import java.util.ArrayList;
83  import java.util.*;
84  import java.util.Date;
85  
86  /**
87   * Created with IntelliJ IDEA.
88   * User: chenchulakshmig
89   * Date: 7/10/13
90   * Time: 12:15 PM
91   * To change this template use File | Settings | File Templates.
92   */
93  public class OLEEResourceSearchServiceImpl implements OLEEResourceSearchService {
94  
95      private static final Logger LOG = Logger.getLogger(OLEEResourceSearchServiceImpl.class);
96      private BusinessObjectService businessObjectService;
97      private ConfigurationService kualiConfigurationService;
98      private OleReqPOCreateDocumentService oleReqPOCreateDocumentService;
99      private OlePurapService olePurapService;
100     protected VendorService vendorService;
101     private final String calendarYearAgo = getParameter(OLEConstants.OLEEResourceRecord.CALENDAR_OR_YEAR_AGO);
102     private final String calendarYearsAgo = getParameter(OLEConstants.OLEEResourceRecord.CALENDAR_OR_YEARS_AGO);
103     private final String monthAgo = getParameter(OLEConstants.OLEEResourceRecord.MONTH_AGO);
104     private final String monthsAgo = getParameter(OLEConstants.OLEEResourceRecord.MONTHS_AGO);
105     private final String weekAgo = getParameter(OLEConstants.OLEEResourceRecord.WEEK_AGO);
106     private final String weeksAgo = getParameter(OLEConstants.OLEEResourceRecord.WEEKS_AGO);
107     private final String dayAgo = getParameter(OLEConstants.OLEEResourceRecord.DAY_AGO);
108     private final String daysAgo = getParameter(OLEConstants.OLEEResourceRecord.DAYS_AGO);
109     private final String firstDayOfYear = getParameter(OLEConstants.OLEEResourceRecord.FIRST_DAY_OF_YEAR);
110     private final String lastDayOfYear = getParameter(OLEConstants.OLEEResourceRecord.LAST_DAY_OF_YEAR);
111     private static final SimpleDateFormat dateFormat = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.CREATED_DATE_FORMAT);
112     private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT);
113     private static final String PLATFORM_URL_START = "platformRecordController?viewId=OLEPlatformRecordView&methodToCall=docHandler&docId=";
114     private static final String PLATFORM_URL_END = "&command=displayDocSearchView&pageId=OLEPlatformRecordView-EventLogTab";
115     private static final String HREF_START = "<a  href='";
116     private static final String HREF_END = "' target='_blank'>Click</a>";
117     private UniversityDateService universityDateService;
118 
119     public BusinessObjectService getBusinessObjectService() {
120         if (businessObjectService == null) {
121             businessObjectService = KRADServiceLocator.getBusinessObjectService();
122         }
123         return businessObjectService;
124     }
125 
126     private DocstoreClientLocator docstoreClientLocator;
127 
128     public DocstoreClientLocator getDocstoreClientLocator() {
129         if (docstoreClientLocator == null) {
130             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
131         }
132         return docstoreClientLocator;
133     }
134 
135     public ConfigurationService getConfigurationService() {
136         if (kualiConfigurationService == null) {
137             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
138         }
139         return kualiConfigurationService;
140     }
141 
142     public OleReqPOCreateDocumentService getOleReqPOCreateDocumentService() {
143         if (oleReqPOCreateDocumentService == null) {
144             oleReqPOCreateDocumentService = SpringContext.getBean(OleReqPOCreateDocumentService.class);
145         }
146         return oleReqPOCreateDocumentService;
147     }
148 
149     public OlePurapService getOlePurapService() {
150         if (olePurapService == null) {
151             olePurapService = SpringContext.getBean(OlePurapService.class);
152         }
153         return olePurapService;
154     }
155 
156     public VendorService getVendorService() {
157         if (vendorService == null) {
158             vendorService = SpringContext.getBean(VendorService.class);
159         }
160         return vendorService;
161     }
162 
163     private ConfigurationService getKualiConfigurationService() {
164         return GlobalResourceLoader.getService("kualiConfigurationService");
165     }
166 
167     @Override
168     public List<OLEEResourceRecordDocument> findMatching(Map<String, List<String>> map, DocumentSearchCriteria.Builder docSearchCriteria) {
169         Map<String, List<String>> attributes = new HashMap<String, List<String>>();
170         if (docSearchCriteria != null) {
171             if (!map.isEmpty()) {
172                 for (String propertyField : map.keySet()) {
173                     if (map.get(propertyField) != null) {
174                         attributes.put(propertyField, map.get(propertyField));
175                     }
176                 }
177             }
178         }
179         docSearchCriteria.setDocumentAttributeValues(attributes);
180         Date currentDate = new Date();
181         docSearchCriteria.setDateCreatedTo(new DateTime(currentDate));
182         DocumentSearchCriteria docSearchCriteriaDTO = docSearchCriteria.build();
183         DocumentSearchResults components = null;
184         components = KEWServiceLocator.getDocumentSearchService().lookupDocuments(GlobalVariables.getUserSession().getPrincipalId(), docSearchCriteriaDTO);
185         List<DocumentSearchResult> docSearchResults = components.getSearchResults();
186         OLEEResourceRecordDocument oleeResourceRecordDocument;
187         List<OLEEResourceRecordDocument> oleeResourceRecordDocumentnew = new ArrayList<OLEEResourceRecordDocument>();
188         if (!docSearchResults.isEmpty()) {
189             for (DocumentSearchResult searchResult : docSearchResults) {
190                 oleeResourceRecordDocument = new OLEEResourceRecordDocument();
191                 oleeResourceRecordDocument.setResultDetails(searchResult, new ArrayList());
192                 if (oleeResourceRecordDocument != null) {
193                     oleeResourceRecordDocumentnew.add(oleeResourceRecordDocument);
194                 }
195             }
196         }
197         return oleeResourceRecordDocumentnew;
198     }
199 
200     @Override
201     public List<OLEEResourceRecordDocument> statusNotNull(List<OLEEResourceRecordDocument> eresourceList, List<String> status) {
202         List<OLEEResourceRecordDocument> eresourceStatusList = new ArrayList<OLEEResourceRecordDocument>();
203         List<String> listOfStatuses = new ArrayList<>();
204         listOfStatuses.addAll(status);
205         for (OLEEResourceRecordDocument oleeResourceRecordDocument : eresourceList) {
206             if (listOfStatuses.contains(oleeResourceRecordDocument.getStatusId())) {
207                 eresourceStatusList.add(oleeResourceRecordDocument);
208             }
209         }
210         return eresourceStatusList;
211     }
212 
213     @Override
214     public List<OLEEResourceRecordDocument> performSearch(List<OLESearchCondition> oleSearchConditionsList) throws Exception {
215         boolean flag = true;
216         Map<String, List<String>> searchCriteriaMap = new HashMap<String, List<String>>();
217         List<OLEEResourceRecordDocument> eresourceList = new ArrayList<OLEEResourceRecordDocument>();
218         List<OLEEResourceRecordDocument> eresourceDocumentList = new ArrayList<OLEEResourceRecordDocument>();
219         DocumentSearchCriteria.Builder docSearchCriteria = DocumentSearchCriteria.Builder.create();
220         docSearchCriteria.setDocumentTypeName(OLEConstants.OLEEResourceRecord.OLE_ERS_DOC);
221         for (int searchCriteriaCnt = 0; searchCriteriaCnt < oleSearchConditionsList.size(); searchCriteriaCnt++) {
222             if (StringUtils.isNotBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy()) && StringUtils.isBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria())) {
223                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.SERACH_CRITERIA_REQUIRED);
224             } else if (StringUtils.isBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy()) && StringUtils.isNotBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria())) {
225                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.SERACH_BY_REQUIRED);
226             } else if (!GlobalVariables.getMessageMap().hasMessages() && StringUtils.isNotBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy()) && StringUtils.isNotBlank(oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria())
227                     && (OLEConstants.OLEEResourceRecord.AND.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator()) || OLEConstants.OLEEResourceRecord.OR.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator()))) {
228                 flag = false;
229                 if (searchCriteriaCnt != 0 && OLEConstants.OLEEResourceRecord.AND.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator())) {
230                     if (!searchCriteriaMap.containsKey(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy())) {
231                         searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria(), searchCriteriaMap);
232                     } else {
233                         searchCriteriaMap.clear();
234                         break;
235                     }
236                 } else {
237                     searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria(), searchCriteriaMap);
238                 }
239                 if (searchCriteriaCnt < oleSearchConditionsList.size() - 1) {
240                     if (StringUtils.isNotBlank(oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchBy()) && !oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchCriteria().isEmpty()) {
241                         if (OLEConstants.OLEEResourceRecord.AND.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator())) {
242                             if (!searchCriteriaMap.containsKey(oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchBy())) {
243                                 searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchCriteria(), searchCriteriaMap);
244                                 if (searchCriteriaCnt < oleSearchConditionsList.size() - 2 && oleSearchConditionsList.get(searchCriteriaCnt + 2).getSearchBy() != null && !oleSearchConditionsList.get(searchCriteriaCnt + 2).getSearchCriteria().isEmpty()) {
245                                     if (OLEConstants.OLEEResourceRecord.AND.equals(oleSearchConditionsList.get(searchCriteriaCnt + 1).getOperator())) {
246                                         searchCriteriaCnt++;
247                                     }
248                                 } else {
249                                     if (searchCriteriaMap.size() > 0) {
250                                         eresourceList = findMatching(searchCriteriaMap, docSearchCriteria);
251                                     }
252                                     break;
253                                 }
254                             } else {
255                                 searchCriteriaMap.clear();
256                                 break;
257                             }
258                         } else if (OLEConstants.OLEEResourceRecord.OR.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator())) {
259                             if (searchCriteriaMap.size() > 0) {
260                                 eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
261                                 eresourceList.addAll(eresourceDocumentList);
262                                 searchCriteriaMap.clear();
263                             }
264                             if (searchCriteriaCnt == oleSearchConditionsList.size() - 2) {
265                                 searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchCriteria(), searchCriteriaMap);
266                                 if (searchCriteriaMap.size() > 0) {
267                                     eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
268                                     eresourceList.addAll(eresourceDocumentList);
269                                     searchCriteriaMap.clear();
270                                 }
271                                 break;
272                             }
273                             if (OLEConstants.OLEEResourceRecord.AND.equals(oleSearchConditionsList.get(searchCriteriaCnt + 1).getOperator())) {
274                                 searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt + 1).getSearchCriteria(), searchCriteriaMap);
275                                 if (searchCriteriaMap.size() > 0) {
276                                     eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
277                                     eresourceList.addAll(eresourceDocumentList);
278                                 }
279                             }
280                         }
281                     } else {
282                         if (!searchCriteriaMap.isEmpty()) {
283                             if (searchCriteriaMap.size() > 0) {
284                                 eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
285                                 eresourceList.addAll(eresourceDocumentList);
286                                 searchCriteriaMap.clear();
287                             }
288                         }
289                     }
290                 }
291                 if (searchCriteriaCnt == oleSearchConditionsList.size() - 1) {
292                     if (searchCriteriaMap.size() > 0) {
293                         eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
294                         eresourceList.addAll(eresourceDocumentList);
295                         searchCriteriaMap.clear();
296                     }
297                 }
298             }
299         }
300         if (flag) {
301             if (!GlobalVariables.getMessageMap().hasMessages()) {
302                 eresourceList = findMatching(searchCriteriaMap, docSearchCriteria);
303             }
304         }
305         if (eresourceList.size() > 0) {
306             for (int searchCriteriaCnt = 0; searchCriteriaCnt < oleSearchConditionsList.size(); searchCriteriaCnt++) {
307                 if (oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy() != null && StringUtils.isNotEmpty(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy()) && !oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria().isEmpty() &&
308                         (OLEConstants.OLEEResourceRecord.NOT.equals(oleSearchConditionsList.get(searchCriteriaCnt).getOperator()))) {
309                     searchCriteriaMap.clear();
310                     searchCriteriaMap = getSearchCriteriaMap(oleSearchConditionsList.get(searchCriteriaCnt).getSearchBy(), oleSearchConditionsList.get(searchCriteriaCnt).getSearchCriteria(), searchCriteriaMap);
311                     if (searchCriteriaMap.size() > 0) {
312                         eresourceDocumentList = findMatching(searchCriteriaMap, docSearchCriteria);
313                     }
314                     List<String> list = new ArrayList<String>();
315                     for (OLEEResourceRecordDocument oleEResourceRecordDocument : eresourceDocumentList) {
316                         int count = 0;
317                         for (OLEEResourceRecordDocument eResourceRecordDocument : eresourceList) {
318                             if (oleEResourceRecordDocument.getDocumentNumber().toString().equalsIgnoreCase(eResourceRecordDocument.getDocumentNumber().toString())) {
319                                 list.add(count + "");
320                             }
321                             count++;
322                         }
323                     }
324                     for (String str : list) {
325                         eresourceList.remove(Integer.parseInt(str));
326                     }
327                 }
328             }
329         }
330         return eresourceList;
331     }
332 
333     public final String getParameter(String parameterName) {
334         ParameterKey parameterKey = ParameterKey.create(OLEConstants.APPL_ID, OLEConstants.SELECT_NMSPC, OLEConstants.SELECT_CMPNT, parameterName);
335         Parameter parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
336         return parameter != null ? parameter.getValue() : null;
337     }
338 
339     public void getEResourcesFields(String eResourceId, OleHoldings eHoldings, WorkEInstanceOlemlForm olemlForm) {
340         ExtentOfOwnership extentOfOwnership = null;
341         if (eHoldings.getExtentOfOwnership().size() > 0) {
342             extentOfOwnership = eHoldings.getExtentOfOwnership().get(0);
343         } else if (extentOfOwnership == null) {
344             extentOfOwnership = new ExtentOfOwnership();
345             eHoldings.getExtentOfOwnership().add(extentOfOwnership);
346         }
347         Coverages coverages = extentOfOwnership.getCoverages();
348         if (coverages == null) {
349             coverages = new Coverages();
350             eHoldings.getExtentOfOwnership().get(0).setCoverages(coverages);
351         }
352         PerpetualAccesses perpetualAccesses = extentOfOwnership.getPerpetualAccesses();
353         if (perpetualAccesses == null) {
354             perpetualAccesses = new PerpetualAccesses();
355             eHoldings.getExtentOfOwnership().get(0).setPerpetualAccesses(perpetualAccesses);
356         }
357         List<Coverage> coverage = coverages.getCoverage();
358         List<PerpetualAccess> perpetualAccess = perpetualAccesses.getPerpetualAccess();
359         //TODO: set the invoice and eResource information
360 //        Invoice invoice = eHoldings.getInvoice();
361         Map ersIdMap = new HashMap();
362         ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceId);
363         OLEEResourceRecordDocument eResourceDocument = getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, ersIdMap);
364         if (eResourceDocument != null && olemlForm.geteResourceId() != null && !olemlForm.geteResourceId().isEmpty()) {
365             olemlForm.setTokenId(eResourceDocument.getDocumentNumber());
366             eHoldings.setEResourceId(eResourceDocument.getOleERSIdentifier());
367             olemlForm.seteResourceTitle(eResourceDocument.getTitle());
368             getAccessLocationFromERS(eResourceDocument, eHoldings, olemlForm);
369             if (eHoldings.getStatisticalSearchingCode() == null) {
370                 StatisticalSearchingCode statisticalSearchingCode = new StatisticalSearchingCode();
371                 statisticalSearchingCode.setCodeValue(eResourceDocument.getOleStatisticalCode() != null ? eResourceDocument.getOleStatisticalCode().getStatisticalSearchingCode() : "");
372                 eHoldings.setStatisticalSearchingCode(statisticalSearchingCode);
373             }
374 //            If subscription fields are blank, then get from the corresponding e-resource screen.
375             if (StringUtils.isBlank(eHoldings.getSubscriptionStatus()) && StringUtils.isNotBlank(eResourceDocument.getSubscriptionStatus())){
376                 eHoldings.setSubscriptionStatus(eResourceDocument.getSubscriptionStatus());
377                 eHoldings.seteResourceSubscriptionStatus(eResourceDocument.getSubscriptionStatus());}
378 
379             if (eHoldings.getInitialSubscriptionStartDate()==null && eResourceDocument.getInitialSubscriptionStartDate()!=null){
380                 eHoldings.seteResourceInitialSubscriptionStartDate(eResourceDocument.getInitialSubscriptionStartDate());
381                 eHoldings.setInitialSubscriptionStartDate(new SimpleDateFormat("MM/dd/yyyy").format(eResourceDocument.getInitialSubscriptionStartDate()));}
382 
383             if(eHoldings.getCurrentSubscriptionEndDate()==null && eResourceDocument.getCurrentSubscriptionEndDate()!=null){
384                 eHoldings.seteResourceCurrentSubscriptionEndDate(eResourceDocument.getCurrentSubscriptionEndDate());
385                 eHoldings.setCurrentSubscriptionEndDate(new SimpleDateFormat("MM/dd/yyyy").format(eResourceDocument.getCurrentSubscriptionEndDate()));}
386 
387             if(eHoldings.getCurrentSubscriptionStartDate()==null && eResourceDocument.getCurrentSubscriptionStartDate()!=null){
388                 eHoldings.setCurrentSubscriptionStartDate(new SimpleDateFormat("MM/dd/yyyy").format(eResourceDocument.getCurrentSubscriptionStartDate()));
389                 eHoldings.seteResourceCurrentSubscriptionStartDate(eResourceDocument.getCurrentSubscriptionStartDate());}
390 
391             if(eHoldings.getCancellationDecisionDate()==null && eResourceDocument.getCancellationDecisionDate()!=null){
392                 eHoldings.setCancellationDecisionDate(new SimpleDateFormat("MM/dd/yyyy").format(eResourceDocument.getCancellationDecisionDate()));
393                 eHoldings.seteResourceCancellationDecisionDate(eResourceDocument.getCancellationDecisionDate());}
394 
395             if(eHoldings.getCancellationEffectiveDate()==null && eResourceDocument.getCancellationEffectiveDate()!=null){
396                 eHoldings.setCancellationEffectiveDate(new SimpleDateFormat("MM/dd/yyyy").format(eResourceDocument.getCancellationEffectiveDate()));
397                 eHoldings.seteResourceCancellationEffectiveDate(eResourceDocument.getCancellationEffectiveDate());}
398 
399             if(StringUtils.isBlank(eHoldings.getCancellationReason()) && StringUtils.isNotBlank(eResourceDocument.getCancellationReason())){
400                 eHoldings.setCancellationReason(eResourceDocument.getCancellationReason());
401                 eHoldings.seteResourceCancellationReason(eResourceDocument.getCancellationReason());}
402 
403             if (coverage.size() != 0) {
404                 if (eResourceDocument.getDefaultCoverage() != null && !eResourceDocument.getDefaultCoverage().isEmpty()) {
405                     if (eResourceDocument.getDefaultCoverage().contains("-")) {
406                         String[] defaultCoverageStart = eResourceDocument.getDefaultCoverage().split(getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR));
407                         String[] covStartSeparator = defaultCoverageStart[0].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
408                         String[] covEndSeparator = defaultCoverageStart[1].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
409                         for (Coverage coverageList : coverage) {
410                             if (StringUtils.isBlank(coverageList.getCoverageEndDate())) {
411                                 if (covEndSeparator.length > 2 && !covEndSeparator[2].isEmpty()) {
412                                     if (covEndSeparator[2].contains("/")) {
413                                         coverageList.setCoverageEndDateFormat(covEndSeparator[2]);
414                                     } else {
415                                         coverageList.setCoverageEndDateString(covEndSeparator[2]);
416                                     }
417                                     coverageList.setCoverageEndDate(covEndSeparator[2]);
418                                 }
419                                 if (covEndSeparator.length > 0 && !covEndSeparator[0].isEmpty()) {
420                                     coverageList.setCoverageEndVolume(covEndSeparator[0]);
421                                 }
422                                 if (covEndSeparator.length > 1 && !covEndSeparator[1].isEmpty()) {
423                                     coverageList.setCoverageEndIssue(covEndSeparator[1]);
424                                 }
425                             }
426                             if (StringUtils.isBlank(coverageList.getCoverageStartDate())) {
427                                 if (covStartSeparator.length > 2 && !covStartSeparator[2].isEmpty()) {
428                                     if (covStartSeparator[2].contains("/")) {
429                                         coverageList.setCoverageStartDateFormat(covStartSeparator[2]);
430                                     } else {
431                                         coverageList.setCoverageStartDateString(covStartSeparator[2]);
432                                     }
433                                     coverageList.setCoverageStartDate(covStartSeparator[2]);
434                                 }
435                                 if (covStartSeparator.length > 0 && !covStartSeparator[0].isEmpty()) {
436                                     coverageList.setCoverageStartVolume(covStartSeparator[0]);
437                                 }
438                                 if (covStartSeparator.length > 1 && !covStartSeparator[1].isEmpty()) {
439                                     coverageList.setCoverageStartIssue(covStartSeparator[1]);
440                                 }
441                             }
442                         }
443                     }
444                 }
445             }
446             if (perpetualAccess.size() != 0) {
447                 if (eResourceDocument.getDefaultPerpetualAccess() != null && !eResourceDocument.getDefaultPerpetualAccess().isEmpty()) {
448                     if (eResourceDocument.getDefaultPerpetualAccess().contains("-")) {
449                         String[] defaultPerAccStart = eResourceDocument.getDefaultPerpetualAccess().split(getParameter(OLEConstants.OLEEResourceRecord.PERPETUAL_ACCESS_DATE_SEPARATOR));
450                         String[] perAccStartSeparator = defaultPerAccStart[0].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
451                         String[] perAccEndSeparator = defaultPerAccStart[1].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
452                         for (PerpetualAccess perpetualAccessList : perpetualAccess) {
453                             if (perpetualAccessList.getPerpetualAccessEndDate() == null) {
454                                 if (perAccEndSeparator.length > 2 && !perAccEndSeparator[2].isEmpty()) {
455                                     if (perAccEndSeparator[2].contains("/")) {
456                                         perpetualAccessList.setPerpetualAccessEndDateFormat(perAccEndSeparator[2]);
457                                     } else {
458                                         perpetualAccessList.setPerpetualAccessEndDateString(perAccEndSeparator[2]);
459                                     }
460                                     perpetualAccessList.setPerpetualAccessEndDate(perAccEndSeparator[2]);
461                                 }
462                                 if (perAccEndSeparator.length > 0 && !perAccEndSeparator[0].isEmpty()) {
463                                     perpetualAccessList.setPerpetualAccessEndVolume(perAccEndSeparator[0]);
464                                 }
465                                 if (perAccEndSeparator.length > 1 && !perAccEndSeparator[1].isEmpty()) {
466                                     perpetualAccessList.setPerpetualAccessEndIssue(perAccEndSeparator[1]);
467                                 }
468                             }
469                             if (perpetualAccessList.getPerpetualAccessStartDate() == null) {
470                                 if (perAccStartSeparator.length > 2 && !perAccStartSeparator[2].isEmpty()) {
471                                     if (perAccStartSeparator[2].contains("/")) {
472                                         perpetualAccessList.setPerpetualAccessStartDateFormat(perAccStartSeparator[2]);
473                                     } else {
474                                         perpetualAccessList.setPerpetualAccessStartDateString(perAccStartSeparator[2]);
475                                     }
476                                     perpetualAccessList.setPerpetualAccessStartDate(perAccStartSeparator[2]);
477                                 }
478                                 if (perAccStartSeparator.length > 0 && !perAccStartSeparator[0].isEmpty()) {
479                                     perpetualAccessList.setPerpetualAccessStartVolume(perAccStartSeparator[0]);
480                                 }
481                                 if (perAccStartSeparator.length > 1 && !perAccStartSeparator[1].isEmpty()) {
482                                     perpetualAccessList.setPerpetualAccessStartIssue(perAccStartSeparator[1]);
483                                 }
484                             }
485                         }
486                     }
487                 }
488             }
489             if (coverage.size() == 0) {
490                 boolean coverageFlag = false;
491                 Coverage cov = new Coverage();
492                 if (eResourceDocument.getDefaultCoverage() != null && !eResourceDocument.getDefaultCoverage().isEmpty()) {
493                     if (eResourceDocument.getDefaultCoverage().contains("-")) {
494                         String[] defaultCoverageStart = eResourceDocument.getDefaultCoverage().split(getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR));
495                         String[] covStartSeparator = defaultCoverageStart[0].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
496                         if (covStartSeparator.length > 2 && !covStartSeparator[2].isEmpty()) {
497                             if(covStartSeparator[2].contains("/")) {
498                                 cov.setCoverageStartDateFormat(covStartSeparator[2]);
499                             } else {
500                                 cov.setCoverageStartDateString(covStartSeparator[2]);
501                             }
502                             cov.setCoverageStartDate(covStartSeparator[2]);
503                             coverageFlag = true;
504                         }
505                         if (covStartSeparator.length > 0 && !covStartSeparator[0].isEmpty()) {
506                             cov.setCoverageStartVolume(covStartSeparator[0]);
507                             coverageFlag = true;
508                         }
509                         if (covStartSeparator.length > 1 && !covStartSeparator[1].isEmpty()) {
510                             cov.setCoverageStartIssue(covStartSeparator[1]);
511                             coverageFlag = true;
512                         }
513                         String[] covEndSeparator = defaultCoverageStart[1].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
514                         if (covEndSeparator.length > 2 && !covEndSeparator[2].isEmpty()) {
515                             if(covEndSeparator[2].contains("/")) {
516                                 cov.setCoverageEndDateFormat(covEndSeparator[2]);
517                             } else {
518                                 cov.setCoverageEndDateString(covEndSeparator[2]);
519                             }
520                             cov.setCoverageEndDate(covEndSeparator[2]);
521                             coverageFlag = true;
522                         }
523                         if (covEndSeparator.length > 0 && !covEndSeparator[0].isEmpty()) {
524                             cov.setCoverageEndVolume(covEndSeparator[0]);
525                             coverageFlag = true;
526                         }
527                         if (covEndSeparator.length > 1 && !covEndSeparator[1].isEmpty()) {
528                             cov.setCoverageEndIssue(covEndSeparator[1]);
529                             coverageFlag = true;
530                         }
531                         if (coverageFlag) {
532                             eHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage().add(cov);
533                         }
534                     }
535                 }
536             }
537             if (perpetualAccess.size() == 0) {
538                 boolean perpetualAccFlag = false;
539                 PerpetualAccess perpetualAcc = new PerpetualAccess();
540                 if (eResourceDocument.getDefaultPerpetualAccess() != null && !eResourceDocument.getDefaultPerpetualAccess().isEmpty()) {
541                     if (eResourceDocument.getDefaultPerpetualAccess().contains("-")) {
542                         String[] defaultPerAccStart = eResourceDocument.getDefaultPerpetualAccess().split(getParameter(OLEConstants.OLEEResourceRecord.PERPETUAL_ACCESS_DATE_SEPARATOR));
543                         String[] perAccStartSeparator = defaultPerAccStart[0].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
544                         if (perAccStartSeparator.length > 2 && !perAccStartSeparator[2].isEmpty()) {
545                             if(perAccStartSeparator[2].contains("/")) {
546                                 perpetualAcc.setPerpetualAccessStartDateFormat(perAccStartSeparator[2]);
547                             } else {
548                                 perpetualAcc.setPerpetualAccessStartDateString(perAccStartSeparator[2]);
549                             }
550                             perpetualAcc.setPerpetualAccessStartDate(perAccStartSeparator[2]);
551                             perpetualAccFlag = true;
552                         }
553                         if (perAccStartSeparator.length > 0 && !perAccStartSeparator[0].isEmpty()) {
554                             perpetualAcc.setPerpetualAccessStartVolume(perAccStartSeparator[0]);
555                             perpetualAccFlag = true;
556                         }
557                         if (perAccStartSeparator.length > 1 && !perAccStartSeparator[1].isEmpty()) {
558                             perpetualAcc.setPerpetualAccessStartIssue(perAccStartSeparator[1]);
559                             perpetualAccFlag = true;
560                         }
561                         String[] perAccEndSeparator = defaultPerAccStart[1].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
562                         if (perAccEndSeparator.length > 2 && !perAccEndSeparator[2].isEmpty()) {
563                             if(perAccEndSeparator[2].contains("/")) {
564                                 perpetualAcc.setPerpetualAccessEndDateFormat(perAccEndSeparator[2]);
565                             } else {
566                                 perpetualAcc.setPerpetualAccessEndDateString(perAccEndSeparator[2]);
567                             }
568                             perpetualAcc.setPerpetualAccessEndDate(perAccEndSeparator[2]);
569                             perpetualAccFlag = true;
570                         }
571                         if (perAccEndSeparator.length > 0 && !perAccEndSeparator[0].isEmpty()) {
572                             perpetualAcc.setPerpetualAccessEndVolume(perAccEndSeparator[0]);
573                             perpetualAccFlag = true;
574                         }
575                         if (perAccEndSeparator.length > 1 && !perAccEndSeparator[1].isEmpty()) {
576                             perpetualAcc.setPerpetualAccessEndIssue(perAccEndSeparator[1]);
577                             perpetualAccFlag = true;
578                         }
579                         if (perpetualAccFlag) {
580                             eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses().getPerpetualAccess().add(perpetualAcc);
581                         }
582                     }
583                 }
584             }
585         } else {
586             getAccessLocationFromEInstance(eHoldings, olemlForm);
587         }
588     }
589 
590     public void removeEResourcesFields(String eResourceId, OleHoldings eHoldings, WorkEInstanceOlemlForm olemlForm) {
591         ExtentOfOwnership extentOfOwnership = null;
592         if (eHoldings.getExtentOfOwnership().size() > 0) {
593             extentOfOwnership = eHoldings.getExtentOfOwnership().get(0);
594         } else if (extentOfOwnership == null) {
595             extentOfOwnership = new ExtentOfOwnership();
596             eHoldings.getExtentOfOwnership().add(extentOfOwnership);
597         }
598         Coverages coverages = extentOfOwnership.getCoverages();
599         if (coverages == null) {
600             coverages = new Coverages();
601             eHoldings.getExtentOfOwnership().get(0).setCoverages(coverages);
602         }
603         List<Coverage> coverage = coverages.getCoverage();
604         Map ersIdMap = new HashMap();
605         ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceId);
606         OLEEResourceRecordDocument eResourceDocument = getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, ersIdMap);
607         if (eResourceDocument != null && olemlForm.geteResourceId() != null && !olemlForm.geteResourceId().isEmpty()) {
608             olemlForm.setTokenId(eResourceDocument.getDocumentNumber());
609             eHoldings.setEResourceId(eResourceDocument.getOleERSIdentifier());
610             olemlForm.seteResourceTitle(eResourceDocument.getTitle());
611             if (coverage.size() != 0) {
612                 if (eResourceDocument.getDefaultCoverage() != null && !eResourceDocument.getDefaultCoverage().isEmpty()) {
613                     if (eResourceDocument.getDefaultCoverage().contains("-")) {
614                         String[] eResDefaultCoverageStart = eResourceDocument.getDefaultCoverage().split(getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR));
615                         String[] eResCovStartSeparator = eResDefaultCoverageStart[0].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
616                         String[] eResCovEndSeparator = eResDefaultCoverageStart[1].split(getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR));
617                         for (Coverage cov : coverage) {
618                             Coverage tempCov = new Coverage();
619                             boolean coverageFlag = false;
620                             if (eResCovStartSeparator.length > 2 && !eResCovStartSeparator[2].isEmpty()) {
621                                 if (eResCovStartSeparator[2].contains("/")) {
622                                     tempCov.setCoverageStartDateFormat(eResCovStartSeparator[2]);
623                                 } else {
624                                     tempCov.setCoverageStartDateString(eResCovStartSeparator[2]);
625                                 }
626                                 tempCov.setCoverageStartDate(eResCovStartSeparator[2]);
627                                 coverageFlag = true;
628                             }
629                             if (eResCovStartSeparator.length > 0 && !eResCovStartSeparator[0].isEmpty()) {
630                                 tempCov.setCoverageStartVolume(eResCovStartSeparator[0]);
631                                 coverageFlag = true;
632                             }
633                             if (eResCovStartSeparator.length > 1 && !eResCovStartSeparator[1].isEmpty()) {
634                                 tempCov.setCoverageStartIssue(eResCovStartSeparator[1]);
635                                 coverageFlag = true;
636                             }
637                             if (eResCovEndSeparator.length > 2 && !eResCovEndSeparator[2].isEmpty()) {
638                                 if (eResCovEndSeparator[2].contains("/")) {
639                                     tempCov.setCoverageEndDateFormat(eResCovEndSeparator[2]);
640                                 } else {
641                                     tempCov.setCoverageEndDateString(eResCovEndSeparator[2]);
642                                 }
643                                 tempCov.setCoverageEndDate(eResCovEndSeparator[2]);
644                                 coverageFlag = true;
645                             }
646                             if (eResCovEndSeparator.length > 0 && !eResCovEndSeparator[0].isEmpty()) {
647                                 tempCov.setCoverageEndVolume(eResCovEndSeparator[0]);
648                                 coverageFlag = true;
649                             }
650                             if (eResCovEndSeparator.length > 1 && !eResCovEndSeparator[1].isEmpty()) {
651                                 tempCov.setCoverageEndIssue(eResCovEndSeparator[1]);
652                                 coverageFlag = true;
653                             }
654                             if (coverageFlag) {
655                                 if (StringUtils.isNotBlank(tempCov.getCoverageStartDateFormat()) && StringUtils.isNotBlank(cov.getCoverageStartDateFormat()) && tempCov.getCoverageStartDateFormat().equals(cov.getCoverageStartDateFormat())) {
656                                     cov.setCoverageStartDateFormat(null);
657                                 }
658                                 if (StringUtils.isNotBlank(tempCov.getCoverageStartDateString()) && StringUtils.isNotBlank(cov.getCoverageStartDateString()) && tempCov.getCoverageStartDateString().equals(cov.getCoverageStartDateString())) {
659                                     cov.setCoverageStartDateString(null);
660                                 }
661                                 if (StringUtils.isNotBlank(tempCov.getCoverageStartDate()) && StringUtils.isNotBlank(cov.getCoverageStartDate()) && tempCov.getCoverageStartDate().equals(cov.getCoverageStartDate())) {
662                                     cov.setCoverageStartDate(null);
663                                 }
664                                 if (StringUtils.isNotBlank(tempCov.getCoverageStartVolume()) && StringUtils.isNotBlank(cov.getCoverageStartVolume()) && tempCov.getCoverageStartVolume().equals(cov.getCoverageStartVolume())) {
665                                     cov.setCoverageStartVolume(null);
666                                 }
667                                 if (StringUtils.isNotBlank(tempCov.getCoverageStartIssue()) && StringUtils.isNotBlank(cov.getCoverageStartIssue()) && tempCov.getCoverageStartIssue().equals(cov.getCoverageStartIssue())) {
668                                     cov.setCoverageStartIssue(null);
669                                 }
670                                 if (StringUtils.isNotBlank(tempCov.getCoverageEndDateFormat()) && StringUtils.isNotBlank(cov.getCoverageEndDateFormat()) && tempCov.getCoverageEndDateFormat().equals(cov.getCoverageEndDateFormat())) {
671                                     cov.setCoverageEndDateFormat(null);
672                                 }
673                                 if (StringUtils.isNotBlank(tempCov.getCoverageEndDateString()) && StringUtils.isNotBlank(cov.getCoverageEndDateString()) && tempCov.getCoverageEndDateString().equals(cov.getCoverageEndDateString())) {
674                                     cov.setCoverageEndDateString(null);
675                                 }
676                                 if (StringUtils.isNotBlank(tempCov.getCoverageEndDate()) && StringUtils.isNotBlank(cov.getCoverageEndDate()) && tempCov.getCoverageEndDate().equals(cov.getCoverageEndDate())) {
677                                     cov.setCoverageEndDate(null);
678                                 }
679                                 if (StringUtils.isNotBlank(tempCov.getCoverageEndVolume()) && StringUtils.isNotBlank(cov.getCoverageEndVolume()) && tempCov.getCoverageEndVolume().equals(cov.getCoverageEndVolume())) {
680                                     cov.setCoverageEndVolume(null);
681                                 }
682                                 if (StringUtils.isNotBlank(tempCov.getCoverageEndIssue()) && StringUtils.isNotBlank(cov.getCoverageEndIssue()) && tempCov.getCoverageEndIssue().equals(cov.getCoverageEndIssue())) {
683                                     cov.setCoverageEndIssue(null);
684                                 }
685                             }
686                         }
687                     }
688                 }
689             }
690         }
691     }
692 
693     public void getAccessLocationFromERS(OLEEResourceRecordDocument eResourceDocument, OleHoldings eHoldings, WorkEInstanceOlemlForm olemlForm) {
694         if (eResourceDocument != null) {
695             HoldingsAccessInformation accessInformation = eHoldings.getHoldingsAccessInformation();
696             if (accessInformation != null&&accessInformation.getAccessLocation()!=null) {
697                 if (olemlForm.getExtendedEHoldingFields().getAccessLocation() != null && olemlForm.getExtendedEHoldingFields().getAccessLocation().size() > 0) {
698                     String accessId = "";
699                     for (String accessLoc : olemlForm.getExtendedEHoldingFields().getAccessLocation()) {
700                         accessId += accessLoc;
701                         accessId += OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR;
702                     }
703                     accessInformation.setAccessLocation(accessId.substring(0, (accessId.lastIndexOf(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR))));
704                     eHoldings.setHoldingsAccessInformation(accessInformation);
705                 }
706                 else{
707                     String accessLocationId = accessInformation.getAccessLocation();
708                     String accessId = "";
709                     if (accessLocationId != null && !accessLocationId.isEmpty()) {
710                         String[] accessLocation = accessLocationId.split(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR);
711                         List<String> accessLocations = new ArrayList<>();
712                         for (String accessLocId : accessLocation) {
713                             olemlForm.getExtendedEHoldingFields().getAccessLocation().add(accessLocId);
714                             accessLocations.add(accessLocId);
715                         }
716                         for (String accessLoc : accessLocations) {
717                             accessId += accessLoc;
718                             accessId += OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR;
719                         }
720                         accessInformation.setAccessLocation(accessId.substring(0, (accessId.lastIndexOf(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR))));
721                     }
722                 }
723             }else {
724                 accessInformation = new HoldingsAccessInformation();
725                 String accessLocationId = eResourceDocument.getAccessLocationId();
726                 String accessId = "";
727                 if (accessLocationId != null && !accessLocationId.isEmpty()) {
728                     String[] accessLocation = accessLocationId.split(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR);
729                     List<String> accessLocations = new ArrayList<>();
730                     for (String accessLocId : accessLocation) {
731                         olemlForm.getExtendedEHoldingFields().getAccessLocation().add(accessLocId);
732                         accessLocations.add(accessLocId);
733                     }
734                     for (String accessLoc : accessLocations) {
735                         accessId += accessLoc;
736                         accessId += OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR;
737                     }
738                     accessInformation.setAccessLocation(accessId.substring(0, (accessId.lastIndexOf(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR))));
739                 }
740 
741             }
742             if (eHoldings.getHoldingsAccessInformation()==null) {
743                 accessInformation.setAuthenticationType(eResourceDocument.getOleAuthenticationType() != null ? eResourceDocument.getOleAuthenticationType().getOleAuthenticationTypeName() : "");
744                 accessInformation.setNumberOfSimultaneousUser(eResourceDocument.getNumOfSimultaneousUsers());
745             }
746             if (eHoldings.getHoldingsAccessInformation()!=null&&eHoldings.getHoldingsAccessInformation().getAuthenticationType()==null) {
747                 accessInformation.setAuthenticationType(eResourceDocument.getOleAuthenticationType() != null ? eResourceDocument.getOleAuthenticationType().getOleAuthenticationTypeName() : "");
748             }
749             if (eHoldings.getHoldingsAccessInformation()!=null&&eHoldings.getHoldingsAccessInformation().getNumberOfSimultaneousUser()==null) {
750                 accessInformation.setNumberOfSimultaneousUser(eResourceDocument.getNumOfSimultaneousUsers());
751             }
752             eHoldings.setHoldingsAccessInformation(accessInformation);
753         }
754     }
755 
756     public void getAccessLocationFromEInstance(OleHoldings eHoldings, WorkEInstanceOlemlForm olemlForm) {
757         HoldingsAccessInformation accessInformation = eHoldings.getHoldingsAccessInformation();
758         List<String> accessLocations = new ArrayList<>();
759         if (accessInformation != null) {
760             if (olemlForm.getExtendedEHoldingFields().getAccessLocation() != null && olemlForm.getExtendedEHoldingFields().getAccessLocation().size() > 0) {
761                 String accessId = "";
762                 for (String accessLoc : olemlForm.getExtendedEHoldingFields().getAccessLocation()) {
763                     accessId += accessLoc;
764                     accessId += OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR;
765                 }
766                 accessInformation.setAccessLocation(accessId.substring(0, (accessId.lastIndexOf(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR))));
767                 eHoldings.setHoldingsAccessInformation(accessInformation);
768             } else if (accessInformation.getAccessLocation() != null && !accessInformation.getAccessLocation().isEmpty()) {
769                 String[] accessId = accessInformation.getAccessLocation().split(OLEConstants.OLEEResourceRecord.ACCESS_LOCATION_SEPARATOR);
770                 for (String accessLoc : accessId) {
771                     accessLocations.add(accessLoc);
772                 }
773                 olemlForm.getExtendedEHoldingFields().setAccessLocation(accessLocations);
774             }
775         }
776     }
777 
778     public Map<String, List<String>> getSearchCriteriaMap(String searchBy, String searchCriteria, Map<String, List<String>> searchCriteriaMap) throws Exception {
779         List<String> listOfBibs = new ArrayList<>();
780         List<String> valueList = new ArrayList<>();
781         org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
782         SearchResponse searchResponse = null;
783         if (searchBy.equals(OLEConstants.OLEEResourceRecord.ERESOURCE_ISBN)) {
784             if ("001".equals(OLEConstants.COMMON_IDENTIFIER_SEARCH)) {
785                 String code = "wbm-" + searchCriteria;
786                 search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id", code), ""));
787             } else {
788                 search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), OLEConstants.COMMON_IDENTIFIER_SEARCH, searchCriteria), ""));
789             }
790 
791 
792             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id"));
793 
794 
795             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
796             for (SearchResult searchResult : searchResponse.getSearchResults()) {
797                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
798                     String fieldName = searchResultField.getFieldName();
799                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
800 
801                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("bibliographic")) {
802                         listOfBibs.add(fieldValue);
803                     }
804                 }
805             }
806 
807 
808             if (listOfBibs.size() > 0) {
809                 valueList.addAll(listOfBibs);
810                 searchCriteriaMap.put(searchBy, valueList);
811 
812 
813             }
814         } else if (searchBy.equals(OLEConstants.OLEEResourceRecord.ERESOURCE_OCLC)) {
815             if ("001".equals(OLEConstants.OCLC_SEARCH)) {
816                 String code = "wbm-" + searchCriteria;
817                 search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id", code), ""));
818             } else {
819                 search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), OLEConstants.OCLC_SEARCH, searchCriteria), ""));
820             }
821             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id"));
822             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
823             for (SearchResult searchResult : searchResponse.getSearchResults()) {
824                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
825                     String fieldName = searchResultField.getFieldName();
826                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
827 
828                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("bibliographic")) {
829                         listOfBibs.add(fieldValue);
830                     }
831                 }
832             }
833             if (listOfBibs.size() > 0) {
834                 valueList.addAll(listOfBibs);
835                 searchCriteriaMap.put(searchBy, valueList);
836             }
837         } else {
838             valueList.add(searchCriteria);
839             searchCriteriaMap.put(searchBy, valueList);
840         }
841         return searchCriteriaMap;
842     }
843 
844     public void getInstanceIdFromERS(List<OLEEResourceInstance> oleERSInstanceList, OleHoldings eHoldings) {
845         String instanceId = "";
846         if (oleERSInstanceList.size() > 0) {
847             for (OLEEResourceInstance oleERSInstance : oleERSInstanceList) {
848                 Map ersIdMap = new HashMap();
849                 ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSInstance.getOleERSIdentifier());
850                 ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_INSTANCE_ID, oleERSInstance.getInstanceId());
851                 List<OLEEResourceInstance> eResourceInstance = (List<OLEEResourceInstance>) getBusinessObjectService().findMatching(OLEEResourceInstance.class, ersIdMap);
852                 if (eResourceInstance.size() > 0) {
853                     for (OLEEResourceInstance eInstanceRec : eResourceInstance) {
854                         instanceId += eInstanceRec.getInstanceId();
855                         instanceId += ",";
856                     }
857                     //TODO: setRelatedInstanceIdentifier
858 //                    eHoldings.setRelatedInstanceIdentifier(instanceId.substring(0, (instanceId.lastIndexOf(","))));
859                 }
860             }
861         }
862     }
863 
864     public void getPOIdFromERS(List<OLEEResourcePO> oleERSPOList, OleHoldings eHoldings) {
865         String poId = "";
866         if (oleERSPOList.size() > 0) {
867             for (OLEEResourcePO oleERSPO : oleERSPOList) {
868                 Map ersIdMap = new HashMap();
869                 ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSPO.getOleERSIdentifier());
870                 ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_PO_ITEM_ID, oleERSPO.getOlePOItemId());
871                 List<OLEEResourcePO> eResourcePO = (List<OLEEResourcePO>) getBusinessObjectService().findMatching(OLEEResourcePO.class, ersIdMap);
872                 if (eResourcePO.size() > 0) {
873                     for (OLEEResourcePO ePORec : eResourcePO) {
874                         poId += ePORec.getOlePOItemId();
875                         poId += ",";
876                     }
877                     //TODO: set PurchaseOrder info
878 //                    eHoldings.setPurchaseOrderId(poId.substring(0, (poId.lastIndexOf(","))));
879                 }
880             }
881         }
882     }
883 
884     public void getEResourcesLicenseFields(String eResourceId, WorkEInstanceOlemlForm eInstanceOlemlForm) {
885         List<OLEEResourceLicense> oleERSLicenses = new ArrayList<OLEEResourceLicense>();
886         Map ersIdMap = new HashMap();
887         ersIdMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, eResourceId);
888         OLEEResourceRecordDocument eResourceDocument = getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, ersIdMap);
889         if (eResourceDocument != null) {
890             oleERSLicenses = eResourceDocument.getOleERSLicenseRequests();
891             if (oleERSLicenses.size() > 0) {
892                 for (OLEEResourceLicense oleeResourceLicense : oleERSLicenses) {
893                     DocumentRouteHeaderValue documentRouteHeaderValue = oleeResourceLicense.getDocumentRouteHeaderValue();
894                     if (documentRouteHeaderValue != null) {
895                         String licenceTitle = documentRouteHeaderValue.getDocTitle();
896                         if (licenceTitle != null && !licenceTitle.isEmpty()) {
897                             licenceTitle = licenceTitle.substring(26);
898                         }
899                         oleeResourceLicense.setDocumentDescription(licenceTitle);
900                     }
901                 }
902                 eInstanceOlemlForm.getExtendedEHoldingFields().setLicense(oleERSLicenses);
903             }
904         }
905     }
906 
907     public OLEEResourceRecordDocument getNewOleERSDoc(OLEEResourceRecordDocument oleERSDoc) {
908         if (oleERSDoc.getOleERSIdentifier() != null && !oleERSDoc.getOleERSIdentifier().isEmpty()) {
909             Map<String, String> tempId = new HashMap<String, String>();
910             tempId.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSDoc.getOleERSIdentifier());
911             OLEEResourceRecordDocument tempDocument = (OLEEResourceRecordDocument) getBusinessObjectService().findByPrimaryKey(OLEEResourceRecordDocument.class, tempId);
912             if (tempDocument != null) {
913                 if (tempDocument.getOleMaterialTypes().size() > 0) {
914                     getBusinessObjectService().delete(tempDocument.getOleMaterialTypes());
915                 }
916                 if (tempDocument.getOleFormatTypes().size() > 0) {
917                     getBusinessObjectService().delete(tempDocument.getOleFormatTypes());
918                 }
919                 if (tempDocument.getOleContentTypes().size() > 0) {
920                     getBusinessObjectService().delete(tempDocument.getOleContentTypes());
921                 }
922                 if (tempDocument.getSelectors().size() > 0) {
923                     getBusinessObjectService().delete(tempDocument.getSelectors());
924                 }
925                 if (tempDocument.getRequestors().size() > 0) {
926                     getBusinessObjectService().delete(tempDocument.getRequestors());
927                 }
928                 if (tempDocument.getReqSelComments().size() > 0) {
929                     getBusinessObjectService().delete(tempDocument.getReqSelComments());
930                 }
931                 if (tempDocument.getOleEResourceVariantTitleList().size() > 0) {
932                     getBusinessObjectService().delete(tempDocument.getOleEResourceVariantTitleList());
933                 }
934                 if (tempDocument.getEresNotes().size() > 0) {
935                     getBusinessObjectService().delete(tempDocument.getEresNotes());
936                 }
937                 if (tempDocument.getOleERSLicenseRequests().size() > 0) {
938                     getBusinessObjectService().delete(tempDocument.getOleERSLicenseRequests());
939                 }
940                 if (tempDocument.getOleERSEventLogs().size() > 0) {
941                     getBusinessObjectService().delete(tempDocument.getOleERSEventLogs());
942                 }
943                 if (tempDocument.getOleERSPOItems().size() > 0) {
944                     getBusinessObjectService().delete(tempDocument.getOleERSPOItems());
945                 }
946                 if (tempDocument.getOleERSInstances().size() > 0) {
947                     getBusinessObjectService().delete(tempDocument.getOleERSInstances());
948                 }
949                 if (tempDocument.getOleERSInvoices().size() > 0) {
950                     getBusinessObjectService().delete(tempDocument.getOleERSInvoices());
951                 }
952                 if (tempDocument.getAccountingLines().size() > 0) {
953                     getBusinessObjectService().delete(tempDocument.getAccountingLines());
954                 }
955             }
956         }
957         return oleERSDoc;
958     }
959 
960    /* public List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList, String docType) {
961         List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
962         for (String instanceId : instanceIdsList) {
963             LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
964             instanceIdMap.put(docType, instanceId);
965             instanceIdMapList.add(instanceIdMap);
966         }
967         QueryService queryService = QueryServiceImpl.getInstance();
968         List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
969         try {
970             workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
971         } catch (Exception ex) {
972             // TODO Auto-generated catch block
973             ex.printStackTrace();
974         }
975         return workBibDocuments;
976     }*/
977 
978     public void getDefaultCovergeDate(OLEEResourceRecordDocument oleERSDoc) {
979         String defaultCoverage = oleERSDoc.getDefaultCoverage();
980         String startCov = "";
981         String endCov = "";
982         String dummyStartCov = "";
983         String dummyEndCov = "";
984         String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
985         String dateSeparator = getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR);
986         if (StringUtils.isNotEmpty(defaultCoverage)) {
987             if (defaultCoverage.contains(separator)) {
988                 String[] defaultCoverageDates = defaultCoverage.split(dateSeparator);
989                 if (defaultCoverageDates[0].contains(separator)) {
990                     String[] startCoverage = defaultCoverageDates[0].split(separator);
991                     if (startCoverage.length > 0) {
992                         if (startCoverage.length > 0 && !startCoverage[0].isEmpty()) {
993                             startCov += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL;
994                             startCov += startCoverage[0];
995                             startCov += separator;
996                             dummyStartCov += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL + startCoverage[0] + separator;
997                         } else {
998                             dummyStartCov += separator;
999                         }
1000                         if (startCoverage.length > 1 && !startCoverage[1].isEmpty()) {
1001                             startCov += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE;
1002                             startCov += startCoverage[1];
1003                             startCov += separator;
1004                             dummyStartCov += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE + startCoverage[1] + separator;
1005                         } else {
1006                             dummyStartCov += separator;
1007                         }
1008                         if (startCoverage.length > 2 && !startCoverage[2].isEmpty()) {
1009                             startCov += OLEConstants.OLEEResourceRecord.SPACE + startCoverage[2] + OLEConstants.OLEEResourceRecord.SPACE;
1010                             startCov += separator;
1011                             dummyStartCov += startCoverage[2] + separator;
1012                         } else {
1013                             dummyStartCov += separator;
1014                         }
1015                         /*for (String covDate : startCoverage) {
1016                             if (covDate != null && !covDate.isEmpty()) {
1017                                 startCov += covDate;
1018 
1019                             }
1020                         }*/
1021                         startCov = startCov.substring(0, startCov.lastIndexOf(separator));
1022                     } else {
1023                         startCov = "";
1024                     }
1025                 }
1026                 if (defaultCoverageDates[1].contains(separator)) {
1027                     String[] endCoverage = defaultCoverageDates[1].split(separator);
1028                     if (endCoverage.length > 0) {
1029                         if (endCoverage.length > 0 && !endCoverage[0].isEmpty()) {
1030                             endCov += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL;
1031                             endCov += endCoverage[0];
1032                             endCov += separator;
1033                             dummyEndCov += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL + endCoverage[0] + separator;
1034                         } else {
1035                             dummyEndCov += separator;
1036                         }
1037                         if (endCoverage.length > 1 && !endCoverage[1].isEmpty()) {
1038                             endCov += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE;
1039                             endCov += endCoverage[1];
1040                             endCov += separator;
1041                             dummyEndCov += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE + endCoverage[1] + separator;
1042                         } else {
1043                             dummyEndCov += separator;
1044                         }
1045                         if (endCoverage.length > 2 && !endCoverage[2].isEmpty()) {
1046                             endCov += OLEConstants.OLEEResourceRecord.SPACE + endCoverage[2];
1047                             endCov += separator;
1048                             dummyEndCov += endCoverage[2] + separator;
1049                         } else {
1050                             dummyEndCov += separator;
1051                         }
1052                         /*for (String endDate : endCoverage) {
1053                             if (endDate != null && !endDate.isEmpty()) {
1054                                 endCov += endDate;
1055                                 endCov += getParameter(OLEConstants.OLEEResourceRecord.DEFAULT_COVERAGE_SEPARATOR);
1056                             }
1057                         }*/
1058                         endCov = endCov.substring(0, endCov.lastIndexOf(separator));
1059                     } else {
1060                         endCov = "";
1061                     }
1062                 }
1063             }
1064             if ((endCov != null && !endCov.isEmpty()) && (startCov != null && !startCov.isEmpty())) {
1065                 oleERSDoc.setDefaultCoverageView(startCov + dateSeparator + endCov);
1066                 oleERSDoc.setDummyDefaultCoverage(dummyStartCov + dateSeparator + dummyEndCov);
1067             } else if (startCov != null && !startCov.isEmpty()) {
1068                 oleERSDoc.setDefaultCoverageView(startCov);
1069                 oleERSDoc.setDummyDefaultCoverage(dummyStartCov);
1070             } else if (endCov != null && !endCov.isEmpty()) {
1071                 oleERSDoc.setDefaultCoverageView(endCov);
1072                 oleERSDoc.setDummyDefaultCoverage(dummyEndCov);
1073             } else {
1074                 oleERSDoc.setDefaultCoverageView(null);
1075                 oleERSDoc.setDummyDefaultCoverage(null);
1076             }
1077         }
1078     }
1079 
1080     public void getDefaultPerpetualAccessDate(OLEEResourceRecordDocument oleERSDoc) {
1081         String defaultPerpetualAcc = oleERSDoc.getDefaultPerpetualAccess();
1082         String startPerAcc = "";
1083         String endPerAcc = "";
1084         String dummyStartPerAcc = "";
1085         String dummyEndPerAcc = "";
1086         String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
1087         String dateSeparator = getParameter(OLEConstants.OLEEResourceRecord.PERPETUAL_ACCESS_DATE_SEPARATOR);
1088         if (StringUtils.isNotEmpty(defaultPerpetualAcc)) {
1089             if (defaultPerpetualAcc.contains(dateSeparator)) {
1090                 String[] defaultPerAccDates = defaultPerpetualAcc.split(dateSeparator);
1091                 if (defaultPerAccDates[0].contains(separator)) {
1092                     String[] startPerpetualAccess = defaultPerAccDates[0].split(separator);
1093                     if (startPerpetualAccess.length > 0) {
1094                         if (startPerpetualAccess.length > 0 && !startPerpetualAccess[0].isEmpty()) {
1095                             startPerAcc += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL;
1096                             startPerAcc += startPerpetualAccess[0];
1097                             startPerAcc += separator;
1098                             dummyStartPerAcc += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL + startPerpetualAccess[0] + separator;
1099                         } else {
1100                             dummyStartPerAcc += separator;
1101                         }
1102                         if (startPerpetualAccess.length > 1 && !startPerpetualAccess[1].isEmpty()) {
1103                             startPerAcc += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE;
1104                             startPerAcc += startPerpetualAccess[1];
1105                             startPerAcc += separator;
1106                             dummyStartPerAcc += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE + startPerpetualAccess[1] + separator;
1107                         } else {
1108                             dummyStartPerAcc += separator;
1109                         }
1110                         if (startPerpetualAccess.length > 2 && !startPerpetualAccess[2].isEmpty()) {
1111                             startPerAcc += OLEConstants.OLEEResourceRecord.SPACE + startPerpetualAccess[2] + OLEConstants.OLEEResourceRecord.SPACE;
1112                             startPerAcc += separator;
1113                             dummyStartPerAcc += startPerpetualAccess[2] + separator;
1114                         } else {
1115                             dummyStartPerAcc += separator;
1116                         }
1117                         /*for (String perAccDate : startPerpetualAccess) {
1118                             if (perAccDate != null && !perAccDate.isEmpty()) {
1119                                 startPerAcc += perAccDate;
1120                                 startPerAcc += getParameter(OLEConstants.OLEEResourceRecord.DEFAULT_PERPETUAL_ACCESS_SEPARATOR);
1121                             }
1122                         }*/
1123                         startPerAcc = startPerAcc.substring(0, startPerAcc.lastIndexOf(separator));
1124                     } else {
1125                         startPerAcc = "";
1126                     }
1127                 }
1128                 if (defaultPerAccDates[1].contains(separator)) {
1129                     String[] endPerpetualAcc = defaultPerAccDates[1].split(separator);
1130                     if (endPerpetualAcc.length > 0) {
1131                         if (endPerpetualAcc.length > 0 && !endPerpetualAcc[0].isEmpty()) {
1132                             endPerAcc += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL;
1133                             endPerAcc += endPerpetualAcc[0];
1134                             endPerAcc += separator;
1135                             dummyEndPerAcc += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL + endPerpetualAcc[0] + separator;
1136                         } else {
1137                             dummyEndPerAcc += separator;
1138                         }
1139                         if (endPerpetualAcc.length > 1 && !endPerpetualAcc[1].isEmpty()) {
1140                             endPerAcc += OLEConstants.OLEEResourceRecord.SPACE + OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE;
1141                             endPerAcc += endPerpetualAcc[1];
1142                             endPerAcc += separator;
1143                             dummyEndPerAcc += OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE + endPerpetualAcc[1] + separator;
1144                         } else {
1145                             dummyEndPerAcc += separator;
1146                         }
1147                         if (endPerpetualAcc.length > 2 && !endPerpetualAcc[2].isEmpty()) {
1148                             endPerAcc += OLEConstants.OLEEResourceRecord.SPACE + endPerpetualAcc[2];
1149                             endPerAcc += separator;
1150                             dummyEndPerAcc += endPerpetualAcc[2] + separator;
1151                         } else {
1152                             dummyEndPerAcc += separator;
1153                         }
1154                         /*for (String perAccDate : endPerpetualAcc) {
1155                             if (perAccDate != null && !perAccDate.isEmpty()) {
1156                                 endPerAcc += perAccDate;
1157                                 endPerAcc += getParameter(OLEConstants.OLEEResourceRecord.DEFAULT_PERPETUAL_ACCESS_SEPARATOR);
1158                             }
1159                         }*/
1160                         endPerAcc = endPerAcc.substring(0, endPerAcc.lastIndexOf(separator));
1161                     } else {
1162                         endPerAcc = "";
1163                     }
1164                 }
1165             }
1166             if ((endPerAcc != null && !endPerAcc.isEmpty()) && (startPerAcc != null && !startPerAcc.isEmpty())) {
1167                 oleERSDoc.setDefaultPerpetualAccessView(startPerAcc + dateSeparator + endPerAcc);
1168                 oleERSDoc.setDummyDefaultPerpetualAccess(dummyStartPerAcc + dateSeparator + dummyEndPerAcc);
1169             } else if (startPerAcc != null && !startPerAcc.isEmpty()) {
1170                 oleERSDoc.setDefaultPerpetualAccessView(startPerAcc);
1171                 oleERSDoc.setDummyDefaultPerpetualAccess(dummyStartPerAcc);
1172             } else if (endPerAcc != null && !endPerAcc.isEmpty()) {
1173                 oleERSDoc.setDefaultPerpetualAccessView(endPerAcc);
1174                 oleERSDoc.setDummyDefaultPerpetualAccess(dummyEndPerAcc);
1175             } else {
1176                 oleERSDoc.setDefaultPerpetualAccessView(null);
1177                 oleERSDoc.setDummyDefaultPerpetualAccess(null);
1178             }
1179 
1180         }
1181     }
1182 
1183     public OLEEResourceRecordDocument saveDefaultCoverageDate(OLEEResourceRecordDocument oleeResourceRecordDocument) {
1184         StringBuffer defaultCoverageDate = new StringBuffer();
1185         OLEEResourceInstance oleERSInstance = oleeResourceRecordDocument.getOleERSInstance();
1186         String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
1187         if (oleERSInstance != null && oleERSInstance.getCovStartDate() != null) {
1188             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovStartVolume()) ? oleERSInstance.getCovStartVolume() + separator : separator);
1189             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovStartIssue()) ? oleERSInstance.getCovStartIssue() + separator : separator);
1190             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovStartDate()) ? oleERSInstance.getCovStartDate() : "");
1191             if (defaultCoverageDate.length() > 0) {
1192                 defaultCoverageDate.append(getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR));
1193             }
1194             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovEndVolume()) ? oleERSInstance.getCovEndVolume() + separator : separator);
1195             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovEndIssue()) ? oleERSInstance.getCovEndIssue() + separator : separator);
1196             defaultCoverageDate.append(StringUtils.isNotEmpty(oleERSInstance.getCovEndDate()) ? oleERSInstance.getCovEndDate() : "");
1197             if (StringUtils.isNotEmpty(defaultCoverageDate)) {
1198                 oleeResourceRecordDocument.setDefaultCoverage(defaultCoverageDate.toString());
1199             }
1200         }
1201         return oleeResourceRecordDocument;
1202     }
1203 
1204     public OLEEResourceRecordDocument saveDefaultPerpetualAccessDate(OLEEResourceRecordDocument oleeResourceRecordDocument) {
1205         StringBuffer defaultPerpetualDate = new StringBuffer();
1206         OLEEResourceInstance oleERSInstance = oleeResourceRecordDocument.getOleERSInstance();
1207         String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
1208         if (oleERSInstance != null && oleERSInstance.getPerpetualAccStartDate() != null) {
1209             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccStartVolume()) ? oleERSInstance.getPerpetualAccStartVolume() + separator : separator);
1210             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccStartIssue()) ? oleERSInstance.getPerpetualAccStartIssue() + separator : separator);
1211             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccStartDate()) ? oleERSInstance.getPerpetualAccStartDate() : "");
1212             if (defaultPerpetualDate.length() > 0) {
1213                 defaultPerpetualDate.append(getParameter(OLEConstants.OLEEResourceRecord.PERPETUAL_ACCESS_DATE_SEPARATOR));
1214             }
1215             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccEndVolume()) ? oleERSInstance.getPerpetualAccEndVolume() + separator : separator);
1216             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccEndIssue()) ? oleERSInstance.getPerpetualAccEndIssue() + separator : separator);
1217             defaultPerpetualDate.append(StringUtils.isNotEmpty(oleERSInstance.getPerpetualAccEndDate()) ? oleERSInstance.getPerpetualAccEndDate() : "");
1218             if (StringUtils.isNotEmpty(defaultPerpetualDate)) {
1219                 oleeResourceRecordDocument.setDefaultPerpetualAccess(defaultPerpetualDate.toString());
1220             }
1221         }
1222         return oleeResourceRecordDocument;
1223     }
1224 
1225     public void getNewInstance(OLEEResourceRecordDocument oleERSDoc, String documentNumber) throws Exception {
1226 
1227         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
1228             HashMap<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
1229             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(documentNumber);
1230             String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
1231             String isbnAndissn = "";
1232             List<String> instanceId = new ArrayList<String>();
1233             List<OLEEResourceInstance> oleeResourceInstances = oleERSDoc.getOleERSInstances();
1234             if (oleeResourceInstances.size() == 0) {
1235                 oleeResourceInstances = new ArrayList<OLEEResourceInstance>();
1236             }
1237             // List<OleCopy> copyList = new ArrayList<>();
1238             //getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(oleEditorResponse.getBib().getId());
1239 
1240             if (oleEditorResponse != null && StringUtils.isNotEmpty(oleEditorResponse.getLinkedInstanceId())) {
1241                 instanceId.add(oleEditorResponse.getLinkedInstanceId());
1242             }
1243             Holdings holdings = null;
1244             if (oleEditorResponse != null && oleERSDoc.getSelectInstance() != null && (oleERSDoc.getSelectInstance().equals(OLEConstants.OLEEResourceRecord.LINK_EXIST_INSTANCE)) || oleERSDoc.getSelectInstance().equals(OLEConstants.OLEEResourceRecord.CREATE_NEW_INSTANCE)) {
1245                 holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleEditorResponse.getLinkedInstanceId());
1246 
1247             }
1248             int index = -1;
1249             if (holdings != null && holdings.getId() != null) {
1250                 HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
1251                 OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
1252                 if (holdings instanceof org.kuali.ole.docstore.common.document.EHoldings) {
1253                     if (oleEditorResponse != null && oleEditorResponse.getLinkedInstanceId().equalsIgnoreCase(holdings.getId())) {
1254                         OLEEResourceInstance oleeResourceInstance = new OLEEResourceInstance();
1255                         if (oleERSDoc.getOleERSInstances() != null && oleERSDoc.getOleERSInstances().size() > 0) {
1256                             for (OLEEResourceInstance eResourceInstance : oleeResourceInstances) {
1257                                 if (eResourceInstance.getInstanceId().equals(oleEditorResponse.getLinkedInstanceId())) {
1258                                     index = oleeResourceInstances.indexOf(eResourceInstance);
1259                                     oleeResourceInstance = eResourceInstance;
1260                                 }
1261                             }
1262                         }
1263                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1264                         oleeResourceInstance.setInstanceTitle(holdings.getBib().getTitle());
1265                         buildInstanceHolding(oleeResourceInstance, oleHoldings, oleERSDoc);
1266                         oleeResourceInstance.setInstancePublisher(oleHoldings.getPublisher());
1267                         if (oleHoldings.getPlatform() != null && StringUtils.isNotBlank(oleHoldings.getPlatform().getPlatformName())) {
1268                             oleeResourceInstance.setPlatformId(oleHoldings.getPlatform().getPlatformName());
1269                         }else {
1270                             oleeResourceInstance.setPlatformId(null);
1271                         }
1272                         // oleeResourceInstance.setPublicDisplayNote(workEInstanceDocument.getPublicDisplayNote());
1273                         StringBuffer urls = new StringBuffer();
1274                         for(Link link :oleHoldings.getLink()){
1275                             urls.append(link.getUrl());
1276                             urls.append(",");
1277                         }
1278                         if(urls.toString().contains(",")){
1279                             String url = urls.substring(0,urls.lastIndexOf(","));
1280                             oleeResourceInstance.setUrl(url);
1281                         }
1282 
1283                         SearchParams searchParams = new SearchParams();
1284                         searchParams.getSearchConditions().add(searchParams.buildSearchCondition(null, searchParams.buildSearchField(OLEConstants.BIB_DOC_TYPE, OLEConstants.BIB_SEARCH, holdings.getBib().getId()), null));
1285                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISBN));
1286                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISSN));
1287                         SearchResponse searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
1288                         SearchResult searchResult;
1289                         if (searchResponse.getSearchResults().size() > 0) {
1290                             searchResult = searchResponse.getSearchResults().get(0);
1291                             searchResult.getSearchResultFields();
1292                             for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1293                                 isbnAndissn += searchResultField.getFieldValue();
1294                                 isbnAndissn += separator;
1295                             }
1296                         }
1297                         if (StringUtils.isNotEmpty(isbnAndissn)) {
1298                             isbnAndissn = isbnAndissn.substring(0, isbnAndissn.lastIndexOf(separator));
1299                         }
1300                         oleeResourceInstance.setOleERSIdentifier(oleERSDoc.getOleERSIdentifier());
1301                         oleeResourceInstance.setIsbn(isbnAndissn);
1302                         oleeResourceInstance.setStatus(oleHoldings.getAccessStatus());
1303                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1304                         oleeResourceInstance.setBibId(holdings.getBib().getId());
1305                         oleeResourceInstance.setInstanceId(holdings.getId());
1306                         oleeResourceInstance.setInstanceFlag("false");
1307                         if (index >= 0) {
1308                             oleeResourceInstances.add(index, oleeResourceInstance);
1309                         } else {
1310                             oleeResourceInstances.add(oleeResourceInstance);
1311                         }
1312                         updateEResInOleCopy(holdings, oleERSDoc);
1313                     }
1314                 }
1315                 if (holdings instanceof org.kuali.ole.docstore.common.document.PHoldings) {
1316                     if (oleEditorResponse != null && oleEditorResponse.getLinkedInstanceId().equalsIgnoreCase(holdings.getId())) {
1317                         OLEEResourceInstance oleeResourceInstance = new OLEEResourceInstance();
1318                         if (oleERSDoc.getOleERSInstances() != null && oleERSDoc.getOleERSInstances().size() > 0) {
1319                             for (OLEEResourceInstance eResourceInstance : oleeResourceInstances) {
1320                                 if (eResourceInstance.getInstanceId().equals(oleEditorResponse.getLinkedInstanceId())) {
1321                                     index = oleeResourceInstances.indexOf(eResourceInstance);
1322                                     oleeResourceInstance = eResourceInstance;
1323                                 }
1324                             }
1325                         }
1326                         oleeResourceInstance.setOleERSIdentifier(oleERSDoc.getOleERSIdentifier());
1327                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1328                         oleeResourceInstance.setInstanceTitle(holdings.getBib().getTitle());
1329                         oleeResourceInstance.setInstancePublisher(holdings.getBib().getPublisher());
1330                         SearchParams searchParams = new SearchParams();
1331                         searchParams.getSearchConditions().add(searchParams.buildSearchCondition(null, searchParams.buildSearchField(OLEConstants.BIB_DOC_TYPE, OLEConstants.BIB_SEARCH, holdings.getBib().getId()), null));
1332                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISBN));
1333                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISSN));
1334                         SearchResponse searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
1335                         SearchResult searchResult;
1336                         if (searchResponse.getSearchResults().size() > 0) {
1337                             searchResult = searchResponse.getSearchResults().get(0);
1338                             searchResult.getSearchResultFields();
1339                             for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1340                                 isbnAndissn += searchResultField.getFieldValue();
1341                                 isbnAndissn += separator;
1342                             }
1343                         }
1344                         if (StringUtils.isNotEmpty(isbnAndissn)) {
1345                             isbnAndissn = isbnAndissn.substring(0, isbnAndissn.lastIndexOf(separator));
1346                         }
1347                         oleeResourceInstance.setIsbn(isbnAndissn);
1348                         oleeResourceInstance.setBibId(holdings.getBib().getId());
1349                         oleeResourceInstance.setInstanceId(holdings.getId());
1350                         oleeResourceInstance.setHoldingsId(oleHoldings.getHoldingsIdentifier());
1351                         oleeResourceInstance.setInstanceFlag("true");
1352                         if (index >= 0) {
1353                             oleeResourceInstances.add(index, oleeResourceInstance);
1354                         } else {
1355                             oleeResourceInstances.add(oleeResourceInstance);
1356                         }
1357                         updateEResInOleCopy(holdings, oleERSDoc);
1358                     }
1359                 }
1360             }
1361             oleERSDoc.setOleERSInstances(oleeResourceInstances);
1362             OleDocstoreResponse.getInstance().setEditorResponse(null);
1363         }
1364     }
1365 
1366     public void getNewInstance(OLEEResourceRecordDocument oleERSDoc, String documentNumber,Holdings holdings) throws Exception {
1367 
1368         if (OleDocstoreResponse.getInstance().getEditorResponse() != null) {
1369             HashMap<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse();
1370             OLEEditorResponse oleEditorResponse = oleEditorResponses.get(documentNumber);
1371             String separator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR);
1372             String isbnAndissn = "";
1373             List<String> instanceId = new ArrayList<String>();
1374             List<OLEEResourceInstance> oleeResourceInstances = oleERSDoc.getOleERSInstances();
1375             if (oleeResourceInstances.size() == 0) {
1376                 oleeResourceInstances = new ArrayList<OLEEResourceInstance>();
1377             }
1378             // List<OleCopy> copyList = new ArrayList<>();
1379             //getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(oleEditorResponse.getBib().getId());
1380 
1381             if (oleEditorResponse != null && StringUtils.isNotEmpty(oleEditorResponse.getLinkedInstanceId())) {
1382                 instanceId.add(oleEditorResponse.getLinkedInstanceId());
1383             }
1384             //Holdings holdings = null;
1385 /*            if (oleEditorResponse != null && oleERSDoc.getSelectInstance() != null && (oleERSDoc.getSelectInstance().equals(OLEConstants.OLEEResourceRecord.LINK_EXIST_INSTANCE)) || oleERSDoc.getSelectInstance().equals(OLEConstants.OLEEResourceRecord.CREATE_NEW_INSTANCE)) {
1386                 holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleEditorResponse.getLinkedInstanceId());
1387 
1388             }*/
1389             int index = -1;
1390             if (holdings != null && holdings.getId() != null) {
1391                 HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
1392                 OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
1393                 if (holdings instanceof org.kuali.ole.docstore.common.document.EHoldings) {
1394                     if (oleEditorResponse != null && oleEditorResponse.getLinkedInstanceId().equalsIgnoreCase(holdings.getId())) {
1395                         OLEEResourceInstance oleeResourceInstance = new OLEEResourceInstance();
1396                         if (oleERSDoc.getOleERSInstances() != null && oleERSDoc.getOleERSInstances().size() > 0) {
1397                             for (OLEEResourceInstance eResourceInstance : oleeResourceInstances) {
1398                                 if (eResourceInstance.getInstanceId().equals(oleEditorResponse.getLinkedInstanceId())) {
1399                                     index = oleeResourceInstances.indexOf(eResourceInstance);
1400                                     oleeResourceInstance = eResourceInstance;
1401                                 }
1402                             }
1403                         }
1404                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1405                         oleeResourceInstance.setInstanceTitle(holdings.getBib().getTitle());
1406                         buildInstanceHolding(oleeResourceInstance, oleHoldings, oleERSDoc);
1407                         oleeResourceInstance.setInstancePublisher(oleHoldings.getPublisher());
1408                         if (oleHoldings.getPlatform() != null && StringUtils.isNotBlank(oleHoldings.getPlatform().getPlatformName())) {
1409                             oleeResourceInstance.setPlatformId(oleHoldings.getPlatform().getPlatformName());
1410                         }else {
1411                             oleeResourceInstance.setPlatformId(null);
1412                         }
1413                         // oleeResourceInstance.setPublicDisplayNote(workEInstanceDocument.getPublicDisplayNote());
1414                         StringBuffer urls = new StringBuffer();
1415                         for(Link link :oleHoldings.getLink()){
1416                             urls.append(link.getUrl());
1417                             urls.append(",");
1418                         }
1419                         if(urls.toString().contains(",")){
1420                             String url = urls.substring(0,urls.lastIndexOf(","));
1421                             oleeResourceInstance.setUrl(url);
1422                         }
1423 
1424                         SearchParams searchParams = new SearchParams();
1425                         searchParams.getSearchConditions().add(searchParams.buildSearchCondition(null, searchParams.buildSearchField(OLEConstants.BIB_DOC_TYPE, OLEConstants.BIB_SEARCH, holdings.getBib().getId()), null));
1426                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISBN));
1427                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISSN));
1428                         SearchResponse searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
1429                         SearchResult searchResult;
1430                         if (searchResponse.getSearchResults().size() > 0) {
1431                             searchResult = searchResponse.getSearchResults().get(0);
1432                             searchResult.getSearchResultFields();
1433                             for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1434                                 isbnAndissn += searchResultField.getFieldValue();
1435                                 isbnAndissn += separator;
1436                             }
1437                         }
1438                         if (StringUtils.isNotEmpty(isbnAndissn)) {
1439                             isbnAndissn = isbnAndissn.substring(0, isbnAndissn.lastIndexOf(separator));
1440                         }
1441                         oleeResourceInstance.setIsbn(isbnAndissn);
1442                         oleeResourceInstance.setStatus(oleHoldings.getAccessStatus());
1443                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1444                         oleeResourceInstance.setBibId(holdings.getBib().getId());
1445                         oleeResourceInstance.setInstanceId(holdings.getId());
1446                         oleeResourceInstance.setInstanceFlag("false");
1447                         oleeResourceInstance.setOleERSIdentifier(oleERSDoc.getOleERSIdentifier());
1448                         if (index >= 0) {
1449                             oleeResourceInstances.add(index, oleeResourceInstance);
1450                         } else {
1451                             oleeResourceInstances.add(oleeResourceInstance);
1452                         }
1453                         updateEResInOleCopy(holdings, oleERSDoc);
1454                     }
1455                 }
1456                 if (holdings instanceof org.kuali.ole.docstore.common.document.PHoldings) {
1457                     if (oleEditorResponse != null && oleEditorResponse.getLinkedInstanceId().equalsIgnoreCase(holdings.getId())) {
1458                         OLEEResourceInstance oleeResourceInstance = new OLEEResourceInstance();
1459                         if (oleERSDoc.getOleERSInstances() != null && oleERSDoc.getOleERSInstances().size() > 0) {
1460                             for (OLEEResourceInstance eResourceInstance : oleeResourceInstances) {
1461                                 if (eResourceInstance.getInstanceId().equals(oleEditorResponse.getLinkedInstanceId())) {
1462                                     index = oleeResourceInstances.indexOf(eResourceInstance);
1463                                     oleeResourceInstance = eResourceInstance;
1464                                 }
1465                             }
1466                         }
1467                         oleeResourceInstance.setOleERSIdentifier(oleERSDoc.getOleERSIdentifier());
1468                         oleeResourceInstance.setSubscriptionStatus(oleHoldings.getSubscriptionStatus());
1469                         oleeResourceInstance.setInstanceTitle(holdings.getBib().getTitle());
1470                         oleeResourceInstance.setInstancePublisher(holdings.getBib().getPublisher());
1471                         SearchParams searchParams = new SearchParams();
1472                         searchParams.getSearchConditions().add(searchParams.buildSearchCondition(null, searchParams.buildSearchField(OLEConstants.BIB_DOC_TYPE, OLEConstants.BIB_SEARCH, holdings.getBib().getId()), null));
1473                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISBN));
1474                         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField(OLEConstants.BIB_DOC_TYPE, OLEConstants.OLEEResourceRecord.ERESOURCE_ISSN));
1475                         SearchResponse searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
1476                         SearchResult searchResult;
1477                         if (searchResponse.getSearchResults().size() > 0) {
1478                             searchResult = searchResponse.getSearchResults().get(0);
1479                             searchResult.getSearchResultFields();
1480                             for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1481                                 isbnAndissn += searchResultField.getFieldValue();
1482                                 isbnAndissn += separator;
1483                             }
1484                         }
1485                         if (StringUtils.isNotEmpty(isbnAndissn)) {
1486                             isbnAndissn = isbnAndissn.substring(0, isbnAndissn.lastIndexOf(separator));
1487                         }
1488                         oleeResourceInstance.setIsbn(isbnAndissn);
1489                         oleeResourceInstance.setBibId(holdings.getBib().getId());
1490                         oleeResourceInstance.setInstanceId(holdings.getId());
1491                         oleeResourceInstance.setHoldingsId(oleHoldings.getHoldingsIdentifier());
1492                         oleeResourceInstance.setInstanceFlag("true");
1493                         if (index >= 0) {
1494                             oleeResourceInstances.add(index, oleeResourceInstance);
1495                         } else {
1496                             oleeResourceInstances.add(oleeResourceInstance);
1497                         }
1498                         updateEResInOleCopy(holdings, oleERSDoc);
1499                     }
1500                 }
1501             }
1502             oleERSDoc.setOleERSInstances(oleeResourceInstances);
1503             OleDocstoreResponse.getInstance().setEditorResponse(null);
1504         }
1505     }
1506 
1507     public void getPOInvoiceForERS(OLEEResourceRecordDocument oleERSDoc) {
1508         try {
1509             Holdings holdings = null;
1510             List<OLEEResourcePO> oleeResourcePOs = new ArrayList<>();
1511             List<OLEEResourcePO> oleLinkedeResourcePOs = new ArrayList<>();
1512             List<OLEEResourceInvoices> oleeResourceInvoiceses = new ArrayList<>();
1513             if (oleERSDoc.getOleERSIdentifier()!=null){
1514                 Map<String, String> criteriaMap = new HashMap<String, String>();
1515                 criteriaMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleERSDoc.getOleERSIdentifier());
1516                 criteriaMap.put(OLEConstants.LOC, "E-Resource");
1517                 List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
1518                         criteriaMap);
1519                 for (OleCopy copy : copies) {
1520                     if (copy.getPoItemId() != null) {
1521                         getPOInvoiceFromCopy(oleERSDoc.getTitle(),copy, oleeResourcePOs, oleeResourceInvoiceses);
1522                     }
1523                 }
1524             }
1525             for(OLELinkedEresource linkedEresource : oleERSDoc.getOleLinkedEresources()){
1526               if(!"parent".equalsIgnoreCase(linkedEresource.getRelationShipType())){
1527                 Map<String, String> criteriaMap = new HashMap<String, String>();
1528                 criteriaMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, linkedEresource.getLinkedERSIdentifier());
1529                 criteriaMap.put(OLEConstants.LOC, "E-Resource");
1530                 List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
1531                         criteriaMap);
1532                 Map<String, String> oleResourceMap = new HashMap<String, String>();
1533                 oleResourceMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, linkedEresource.getLinkedERSIdentifier());
1534                 List<OLEEResourceRecordDocument> oleeResourceRecordDocumentList = (List<OLEEResourceRecordDocument>)getBusinessObjectService().findMatching(OLEEResourceRecordDocument.class,oleResourceMap);
1535                 linkedEresource.setOleeResourceRecordDocument(oleeResourceRecordDocumentList.get(0));
1536                 for (OleCopy copy : copies) {
1537                     if (copy.getPoItemId() != null) {
1538                         getPOInvoiceFromCopy(linkedEresource.getOleeResourceRecordDocument().getTitle(),copy, oleLinkedeResourcePOs, oleeResourceInvoiceses);
1539                         oleeResourcePOs.addAll(oleLinkedeResourcePOs);
1540                     }
1541                 }
1542               }
1543             }
1544             for (OLEEResourceInstance oleeResourceInstance : oleERSDoc.getOleERSInstances()) {
1545                 holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleeResourceInstance.getInstanceId());
1546                 if (holdings != null) {
1547                     Map<String, String> criteriaMap = new HashMap<String, String>();
1548                     criteriaMap.put(OLEConstants.INSTANCE_ID, holdings.getId());
1549                     List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
1550                             criteriaMap);
1551                     for (OleCopy copy : copies) {
1552                         if (copy.getPoItemId() != null) {
1553                             getPOInvoiceFromCopy(holdings.getBib().getTitle(),copy, oleeResourcePOs, oleeResourceInvoiceses);
1554                         }
1555                     }
1556                 }
1557             }
1558             for (OLEEResourceInstance oleeResourceInstance : oleERSDoc.geteRSInstances()) {
1559                 holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(oleeResourceInstance.getInstanceId());
1560                 if (holdings != null) {
1561                     Map<String, String> criteriaMap = new HashMap<String, String>();
1562                     criteriaMap.put(OLEConstants.INSTANCE_ID, holdings.getId());
1563                     List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
1564                             criteriaMap);
1565                     for (OleCopy copy : copies) {
1566                         if (copy.getPoItemId() != null) {
1567                             getPOInvoiceFromCopy(holdings.getBib().getTitle(),copy, oleLinkedeResourcePOs, oleeResourceInvoiceses);
1568                         }
1569                     }
1570                 }
1571             }
1572             oleERSDoc.setOleERSPOItems(oleeResourcePOs);
1573             oleERSDoc.setLinkedERSPOItems(oleLinkedeResourcePOs);
1574             oleERSDoc.setOleERSInvoices(oleeResourceInvoiceses);
1575             getPOAndInvoiceItemsWithoutDuplicate(oleERSDoc);
1576         } catch (Exception e) {
1577             LOG.error("Exception " + e);
1578         }
1579     }
1580 
1581     private void getPOInvoiceFromCopy(String title, OleCopy copy, List<OLEEResourcePO> oleeResourcePOs, List<OLEEResourceInvoices> oleeResourceInvoiceses) {
1582 
1583         Map<String, String> criteriaPOIdMap = new HashMap<String, String>();
1584         criteriaPOIdMap.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, copy.getPoItemId().toString());
1585         List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, criteriaPOIdMap);
1586         if (olePurchaseOrderItems.size() > 0) {
1587             for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
1588                 if (olePurchaseOrderItem != null && olePurchaseOrderItem.isItemActiveIndicator()) {
1589                     Map map = new HashMap();
1590                     map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
1591                     OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, map);
1592                     if (olePurchaseOrderDocument != null) {
1593                         DocumentHeader documentHeader = (FinancialSystemDocumentHeader) SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(olePurchaseOrderDocument.getDocumentNumber());
1594                         if (documentHeader != null) {
1595                             olePurchaseOrderDocument.setDocumentHeader(documentHeader);
1596                         }
1597                         if (olePurchaseOrderDocument.getApplicationDocumentStatus() != null && !olePurchaseOrderDocument.getApplicationDocumentStatus().equals("Retired Version")) {
1598                             OLEEResourcePO oleeResourcePO = new OLEEResourcePO();
1599                             oleeResourcePO.setTitle(title);
1600                             oleeResourcePO.setOlePOItemId(olePurchaseOrderDocument.getPurapDocumentIdentifier());
1601                             oleeResourcePO.setPoStatus(olePurchaseOrderDocument.getApplicationDocumentStatus());
1602                             if(StringUtils.isNotBlank(olePurchaseOrderItem.getPurposeId())) {
1603                                 Map<String,String> purposeMap = new HashMap<>();
1604                                 purposeMap.put(OLEConstants.OlePurchaseOrderPurpose.PURCHASE_ORDER_PURPOSE_ID, olePurchaseOrderItem.getPurposeId());
1605                                 OlePurchaseOrderPurpose olePurchaseOrderPurpose = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderPurpose.class, purposeMap);
1606                                 if(olePurchaseOrderPurpose != null) {
1607                                     oleeResourcePO.setPurpose(olePurchaseOrderPurpose.getPurchaseOrderPurposeCode());
1608                                 }
1609                             }
1610                             Integer poCreatedYear = olePurchaseOrderDocument.getPostingYear();
1611                             Integer currentYear = Calendar.getInstance().get(Calendar.YEAR);
1612                             if (currentYear.compareTo(poCreatedYear) == 0) {
1613                                 oleeResourcePO.setPaidAmountCurrentFY(olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
1614                             } else if (currentYear.compareTo(poCreatedYear) == 1) {
1615                                 oleeResourcePO.setPaidAmountPreviousFY(olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
1616                             } else if (currentYear.compareTo(poCreatedYear) > 1) {
1617                                 oleeResourcePO.setPaidAmountTwoYearsPreviousFY(olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
1618                             }
1619                             oleeResourcePO.setVendorDetail(olePurchaseOrderDocument.getVendorDetail());
1620                             oleeResourcePOs.add(oleeResourcePO);
1621                         }
1622                     }
1623                 }
1624             }
1625         }
1626 
1627 
1628         Map<String, String> criteriaInvIdMap = new HashMap<String, String>();
1629         criteriaInvIdMap.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, copy.getPoItemId().toString());
1630         List<OleInvoiceItem> oleInvoiceItems = (List<OleInvoiceItem>) getBusinessObjectService().findMatching(OleInvoiceItem.class, criteriaInvIdMap);
1631         if (oleInvoiceItems.size() > 0) {
1632             for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
1633                 OLEEResourceInvoices oleEResInvoice = new OLEEResourceInvoices();
1634                 oleEResInvoice.setInvoiceId(oleInvoiceItem.getItemIdentifier().toString());
1635                 OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceItem.getInvoiceDocument();
1636                 if (oleInvoiceItem.getInvoiceDocument() != null) {
1637                     oleEResInvoice.setInvoiceNumber(oleInvoiceItem.getInvoiceDocument().getDocumentNumber());
1638                     oleEResInvoice.setInvoiceDate(oleInvoiceItem.getInvoiceDocument().getInvoiceDate());
1639                     oleEResInvoice.setVendorName(oleInvoiceItem.getInvoiceDocument().getVendorName());
1640                     if (SpringContext.getBean(DocumentHeaderService.class) != null) {
1641                         oleInvoiceDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(oleInvoiceDocument.getDocumentNumber()));
1642                         oleEResInvoice.setInvoiceStatus(oleInvoiceDocument.getApplicationDocumentStatus());
1643                     }
1644                 }
1645                 oleEResInvoice.setInvoicedAmount(oleInvoiceItem.getExtendedPrice().toString());
1646                 Map map = new HashMap();
1647                 map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, oleInvoiceItem.getItemIdentifier());
1648                 OlePaymentRequestItem olePaymentRequestItem = getBusinessObjectService().findByPrimaryKey(OlePaymentRequestItem.class, map);
1649                 if (olePaymentRequestItem != null) {
1650                     oleEResInvoice.setPaidDate(olePaymentRequestItem.getPaymentRequestDocument().getPaymentRequestPayDate());
1651                 }
1652                 //invoice note
1653                 if (CollectionUtils.isNotEmpty(oleInvoiceItem.getNotes())) {
1654                     StringBuffer invoiceNotes = new StringBuffer();
1655                     for (OleInvoiceNote oleInvoiceNote : oleInvoiceItem.getNotes()) {
1656                         invoiceNotes.append(oleInvoiceNote.getNote());
1657                         invoiceNotes.append(OLEConstants.COMMA);
1658                         invoiceNotes.append(' ');
1659                     }
1660                     if (invoiceNotes.length() > 0) {
1661                         invoiceNotes.deleteCharAt(invoiceNotes.length() - 2);
1662                         oleEResInvoice.setInvoiceNote(invoiceNotes.toString());
1663                     }
1664                 }
1665                 oleEResInvoice.setVendorDetail(oleInvoiceDocument.getVendorDetail());
1666 
1667                 //accounting lines
1668                 if (oleInvoiceItem.getSourceAccountingLines() != null && oleInvoiceItem.getSourceAccountingLines().size() > 0) {
1669                     List<OLEEResourceInvoiceAccountingLine> oleeResourceInvoiceAccountingLineList = new ArrayList<>();
1670                     for (PurApAccountingLine accountingLine : oleInvoiceItem.getSourceAccountingLines()) {
1671                         OLEEResourceInvoiceAccountingLine oleeResourceInvoiceAccountingLine = new OLEEResourceInvoiceAccountingLine();
1672                         oleeResourceInvoiceAccountingLine.setChartOfAccountsCode(accountingLine.getChartOfAccountsCode());
1673                         oleeResourceInvoiceAccountingLine.setAccountNumber(accountingLine.getAccountNumber());
1674                         oleeResourceInvoiceAccountingLine.setSubAccountNumber(accountingLine.getSubAccountNumber());
1675                         oleeResourceInvoiceAccountingLine.setFinancialObjectCode(accountingLine.getFinancialObjectCode());
1676                         oleeResourceInvoiceAccountingLine.setFinancialSubObjectCode(accountingLine.getFinancialSubObjectCode());
1677                         oleeResourceInvoiceAccountingLine.setProjectCode(accountingLine.getProjectCode());
1678                         oleeResourceInvoiceAccountingLine.setOrganizationReferenceId(accountingLine.getOrganizationReferenceId());
1679                         oleeResourceInvoiceAccountingLine.setAmount(accountingLine.getAmount());
1680                         oleeResourceInvoiceAccountingLine.setAccountLinePercent(accountingLine.getAccountLinePercent());
1681                         oleeResourceInvoiceAccountingLineList.add(oleeResourceInvoiceAccountingLine);
1682                     }
1683                     oleEResInvoice.setAccountingLines(oleeResourceInvoiceAccountingLineList);
1684                 }
1685                 oleeResourceInvoiceses.add(oleEResInvoice);
1686             }
1687         }
1688     }
1689 
1690     public void getHoldingsField(OLEEResourceInstance oleeResourceInstance, OleHoldings oleHoldings) {
1691         Map<String,String> map=new HashMap();
1692         map.put("oleERSIdentifier", oleHoldings.getEResourceId());
1693         List<OLEEResourceRecordDocument> oleeResourceRecordDocuments = (List<OLEEResourceRecordDocument>) getBusinessObjectService().findMatching(OLEEResourceRecordDocument.class, map);
1694         OLEEResourceRecordDocument oleeResourceRecordDocument =null;
1695         if(oleeResourceRecordDocuments.size() > 0){
1696             oleeResourceRecordDocument = oleeResourceRecordDocuments.get(0);
1697         }
1698         buildInstanceHolding(oleeResourceInstance, oleHoldings, oleeResourceRecordDocuments.get(0));
1699     }
1700 
1701     private void buildInstanceHolding(OLEEResourceInstance oleeResourceInstance, OleHoldings oleHoldings, OLEEResourceRecordDocument oleeResourceRecordDocument) {
1702         String start="";
1703         String end="";
1704         String holdings = "";
1705         String startDate = "";
1706         String endDate = "";
1707         String space = OLEConstants.OLEEResourceRecord.SPACE;
1708         String separator = getParameter(OLEConstants.OLEEResourceRecord.COVERAGE_DATE_SEPARATOR);
1709         String commaSeparator = getParameter(OLEConstants.OLEEResourceRecord.COMMA_SEPARATOR) + space;
1710         if(oleeResourceRecordDocument != null) {
1711             String defaultCoverage = oleeResourceRecordDocument.getDefaultCoverage();
1712             if (defaultCoverage != null) {
1713                 String[] defaultCovDates = defaultCoverage.split("-");
1714                 String defCovStartDat = defaultCovDates.length > 0 ? defaultCovDates[0] : "";
1715                 if (!defCovStartDat.isEmpty()) {
1716                     String[] covStartDate = defCovStartDat.split(",");
1717                     if (covStartDate.length > 2 && !covStartDate[2].isEmpty()) {
1718                         start = covStartDate[2];
1719                     }
1720                 }
1721                 String defCovEndDat = defaultCovDates.length > 1 ? defaultCovDates[1] : "";
1722                 if (!defCovEndDat.isEmpty()) {
1723                     String[] covEndDate = defCovEndDat.split(",");
1724                     if (covEndDate.length > 2 && !covEndDate[2].isEmpty()) {
1725                         end = covEndDate[2];
1726                     }
1727                 }
1728             }
1729         }
1730         if (oleHoldings.getExtentOfOwnership().size() > 0 && oleHoldings.getExtentOfOwnership().get(0).getCoverages() != null) {
1731             List<Coverage> coverageDates = oleHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage();
1732             if (coverageDates.size() > 0) {
1733                 for (Coverage coverageDate : coverageDates) {
1734                     startDate = coverageDate.getCoverageStartDate();
1735                     endDate = coverageDate.getCoverageEndDate();
1736                     if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
1737                         holdings += startDate + space + separator + space + endDate;
1738                         holdings += commaSeparator;
1739                     } else if (startDate != null && !startDate.isEmpty()) {
1740                         holdings += startDate + space + separator + space + end;
1741                         holdings += commaSeparator;
1742                     } else if (endDate != null && !endDate.isEmpty()) {
1743                         holdings += start + space + separator + space + endDate;
1744                         holdings += commaSeparator;
1745                     }
1746                 }
1747             }
1748         } else {
1749             if (start != null && !start.isEmpty() && end != null && !end.isEmpty()) {
1750                 holdings += start + space + separator + space + end;
1751                 holdings += commaSeparator;
1752             }
1753             else if(start != null && !start.isEmpty()){
1754                 holdings += start + space + separator + space + end;
1755                 holdings += commaSeparator;
1756             }
1757             else if(end != null && !end.isEmpty()){
1758                 holdings += start + space + separator + space + end;
1759                 holdings += commaSeparator;
1760             }
1761         }
1762         if (holdings != null && !holdings.isEmpty()) {
1763             holdings = holdings.substring(0, holdings.lastIndexOf(commaSeparator));
1764         }
1765         oleeResourceInstance.setInstanceHoldings(holdings);
1766     }
1767 
1768     @Override
1769     public void getDefaultCovDatesToPopup(OLEEResourceRecordDocument oleeResourceRecordDocument, String defaultCov) {
1770         String[] defaultCovDates = defaultCov.split("-");
1771         String defCovStartDat = defaultCovDates.length > 0 ? defaultCovDates[0] : "";
1772         if (oleeResourceRecordDocument.getOleERSInstance() != null) {
1773             if (!defCovStartDat.isEmpty()) {
1774                 String[] covStartDate = defCovStartDat.split(",");
1775                 if (covStartDate.length > 0 && !covStartDate[0].isEmpty()) {
1776                     oleeResourceRecordDocument.getOleERSInstance().setCovStartVolume(covStartDate[0].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL) ? covStartDate[0].substring(7, covStartDate[0].length()) : "");
1777                 }
1778                 if (covStartDate.length > 1 && !covStartDate[1].isEmpty()) {
1779                     oleeResourceRecordDocument.getOleERSInstance().setCovStartIssue(covStartDate[1].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE) ? covStartDate[1].substring(6, covStartDate[1].length()) : "");
1780                 }
1781                 if (covStartDate.length > 2 && !covStartDate[2].isEmpty()) {
1782                     oleeResourceRecordDocument.getOleERSInstance().setCovStartDate(covStartDate[2]);
1783                     oleeResourceRecordDocument.setCovStartDate(oleeResourceRecordDocument.getOleERSInstance().getCovStartDate());
1784                 }
1785             }
1786             String defCovEndDat = defaultCovDates.length > 1 ? defaultCovDates[1] : "";
1787             if (!defCovEndDat.isEmpty()) {
1788                 String[] covEndDate = defCovEndDat.split(",");
1789                 if (covEndDate.length > 0 && !covEndDate[0].isEmpty()) {
1790                     oleeResourceRecordDocument.getOleERSInstance().setCovEndVolume(covEndDate[0].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL) ? covEndDate[0].substring(7, covEndDate[0].length()) : "");
1791                 }
1792                 if (covEndDate.length > 1 && !covEndDate[1].isEmpty()) {
1793                     oleeResourceRecordDocument.getOleERSInstance().setCovEndIssue(covEndDate[1].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE) ? covEndDate[1].substring(6, covEndDate[1].length()) : "");
1794                 }
1795                 if (covEndDate.length > 2 && !covEndDate[2].isEmpty()) {
1796                     oleeResourceRecordDocument.getOleERSInstance().setCovEndDate(covEndDate[2]);
1797                     oleeResourceRecordDocument.setCovEndDate(oleeResourceRecordDocument.getOleERSInstance().getCovEndDate());
1798                 }
1799             }
1800         }
1801     }
1802 
1803     @Override
1804     public void getDefaultPerAccDatesToPopup(OLEEResourceRecordDocument oleeResourceRecordDocument, String defaultPerpetualAcc) {
1805         String[] defaultPerAccDates = defaultPerpetualAcc.split("-");
1806         String defPerAccStartDat = defaultPerAccDates.length > 0 ? defaultPerAccDates[0] : "";
1807         if (oleeResourceRecordDocument.getOleERSInstance() != null) {
1808             if (!defPerAccStartDat.isEmpty()) {
1809                 String[] perAccStartDate = defPerAccStartDat.split(",");
1810                 if (perAccStartDate.length > 0 && !perAccStartDate[0].isEmpty()) {
1811                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccStartVolume(perAccStartDate[0].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL) ? perAccStartDate[0].substring(7, perAccStartDate[0].length()) : "");
1812                 }
1813                 if (perAccStartDate.length > 1 && !perAccStartDate[1].isEmpty()) {
1814                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccStartIssue(perAccStartDate[1].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE) ? perAccStartDate[1].substring(6, perAccStartDate[1].length()) : "");
1815                 }
1816                 if (perAccStartDate.length > 2 && !perAccStartDate[2].isEmpty()) {
1817                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccStartDate(perAccStartDate[2]);
1818                     oleeResourceRecordDocument.setPerAccStartDate(oleeResourceRecordDocument.getOleERSInstance().getPerpetualAccStartDate());
1819                 }
1820             }
1821             String defPerAccEndDat = defaultPerAccDates.length > 1 ? defaultPerAccDates[1] : "";
1822             if (!defPerAccEndDat.isEmpty()) {
1823                 String[] perAccEndDate = defPerAccEndDat.split(",");
1824                 if (perAccEndDate.length > 0 && !perAccEndDate[0].isEmpty()) {
1825                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccEndVolume(perAccEndDate[0].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_VOL) ? perAccEndDate[0].substring(7, perAccEndDate[0].length()) : "");
1826                 }
1827                 if (perAccEndDate.length > 1 && !perAccEndDate[1].isEmpty()) {
1828                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccEndIssue(perAccEndDate[1].contains(OLEConstants.OLEEResourceRecord.DEFAULT_DATE_ISSUE) ? perAccEndDate[1].substring(6, perAccEndDate[1].length()) : "");
1829                 }
1830                 if (perAccEndDate.length > 2 && !perAccEndDate[2].isEmpty()) {
1831                     oleeResourceRecordDocument.getOleERSInstance().setPerpetualAccEndDate(perAccEndDate[2]);
1832                     oleeResourceRecordDocument.setPerAccEndDate(oleeResourceRecordDocument.getOleERSInstance().getPerpetualAccEndDate());
1833                 }
1834             }
1835         }
1836     }
1837 
1838     public boolean validateEResourceDocument(OLEEResourceRecordDocument oleeResourceRecordDocument) {
1839         boolean flag = false;
1840         boolean isSelectorBlank = false;
1841         boolean isRequestorBlank = false;
1842         boolean isReqSelCommentBlank = false;
1843         boolean isVariantTitleBlank = false;
1844         if (oleeResourceRecordDocument.getOleMaterialTypes().size() == 0) {
1845             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_MATERIAL_TYPES, OLEConstants.OLEEResourceRecord.MATERIAL_TYPE_REQUIRED, new String[]{"Material Type"});
1846             flag = true;
1847         }
1848         if (oleeResourceRecordDocument.getOleFormatTypes().size() == 0) {
1849             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_FORMAT_TYPES, OLEConstants.OLEEResourceRecord.FORMAT_TYPE_REQUIRED, new String[]{"Format Type"});
1850             flag = true;
1851         }
1852         if (oleeResourceRecordDocument.getOleContentTypes().size() == 0) {
1853             GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.DOCUMENT_CONTENT_TYPES, OLEConstants.OLEEResourceRecord.CONTENT_TYPE_REQUIRED, new String[]{"Content Type"});
1854             flag = true;
1855         }
1856         if (StringUtils.isNotBlank(oleeResourceRecordDocument.getVendorName())) {
1857             Map vendorMap = new HashMap();
1858             vendorMap.put(OLEConstants.VENDOR_NAME, oleeResourceRecordDocument.getVendorName());
1859             List<VendorDetail> vendorDetails = (List<VendorDetail>) getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
1860             if (vendorDetails != null && vendorDetails.size() > 0) {
1861                 oleeResourceRecordDocument.setVendorId(vendorDetails.get(0).getVendorNumber());
1862                 oleeResourceRecordDocument.setActiveVendor(vendorDetails.get(0).isActiveIndicator());
1863             } else {
1864                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.OLEERMAINTAB_OVERVIEW, OLEConstants.OLEEResourceRecord.INVALID_VENDOR);
1865                 flag = true;
1866             }
1867         }else {
1868             oleeResourceRecordDocument.setVendorId(null);
1869         }
1870         oleeResourceRecordDocument.setPublisherId(null);
1871         if (StringUtils.isNotBlank(oleeResourceRecordDocument.getPublisher())) {
1872             Map vendorMap = new HashMap();
1873             vendorMap.put(OLEConstants.VENDOR_NAME, oleeResourceRecordDocument.getPublisher());
1874             List<VendorDetail> vendorDetails = (List<VendorDetail>) getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
1875             if (vendorDetails != null && vendorDetails.size() > 0) {
1876                 oleeResourceRecordDocument.setPublisherId(vendorDetails.get(0).getVendorNumber());
1877                 oleeResourceRecordDocument.setActivePublisher(vendorDetails.get(0).isActiveIndicator());
1878             } else {
1879                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(OLEConstants.OLEEResourceRecord.OLEERMAINTAB_OVERVIEW, OLEConstants.OLEEResourceRecord.INVALID_PUBLISHER);
1880                 flag = true;
1881             }
1882         }
1883         if (oleeResourceRecordDocument.getRequestors().size() > 0) {
1884             for (OLEEResourceRequestor oleeResourceRequestor : oleeResourceRecordDocument.getRequestors()) {
1885                 if (oleeResourceRequestor.getRequestorId() == null || oleeResourceRequestor.getRequestorId().equalsIgnoreCase("")) {
1886                     if (oleeResourceRecordDocument.getRequestors().size() != 1) {
1887                         isRequestorBlank = true;
1888                     }
1889                 }
1890             }
1891             if (isRequestorBlank) {
1892                 GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEEResourceRecord.REQUESTOR_SECTION_ID, OLEConstants.OLEEResourceRecord.SHOULD_NOT_BLANK, new String[]{"Requestor Type"});
1893                 flag = true;
1894             }
1895         }
1896         if (oleeResourceRecordDocument.getSelectors().size() > 0) {
1897             for (OLEEResourceSelector oleeResourceSelector : oleeResourceRecordDocument.getSelectors()) {
1898                 if (oleeResourceSelector.getSelectorId() == null || oleeResourceSelector.getSelectorId().equalsIgnoreCase("")) {
1899                     if (oleeResourceRecordDocument.getSelectors().size() != 1) {
1900                         isSelectorBlank = true;
1901                     }
1902 
1903                 }
1904             }
1905             if (isSelectorBlank) {
1906                 GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEEResourceRecord.SELECTOR_SECTION_ID, OLEConstants.OLEEResourceRecord.SHOULD_NOT_BLANK, new String[]{"Selector Type"});
1907                 flag = true;
1908             }
1909         }
1910         if (oleeResourceRecordDocument.getReqSelComments().size() > 0) {
1911             for (OLEEResourceReqSelComments oleeResourceReqSelComments : oleeResourceRecordDocument.getReqSelComments()) {
1912                 if (oleeResourceReqSelComments.getOleReqSelComments() == null || oleeResourceReqSelComments.getOleReqSelComments().equalsIgnoreCase("")) {
1913                     if (oleeResourceRecordDocument.getReqSelComments().size() != 1) {
1914                         isReqSelCommentBlank = true;
1915                     }
1916                 }
1917             }
1918             if (isReqSelCommentBlank) {
1919                 GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEEResourceRecord.REQUESTOR_SELECTOR_COMMENT_SECTION_ID, OLEConstants.OLEEResourceRecord.SHOULD_NOT_BLANK, new String[]{"RequestorSelectorComment"});
1920                 flag = true;
1921             }
1922         }
1923         if (oleeResourceRecordDocument.getOleEResourceVariantTitleList().size() > 0) {
1924             for (OLEEResourceVariantTitle oleEResourceVariantTitle : oleeResourceRecordDocument.getOleEResourceVariantTitleList()) {
1925                 if (oleEResourceVariantTitle.getOleVariantTitle() == null || oleEResourceVariantTitle.getOleVariantTitle().equalsIgnoreCase("")) {
1926                     if (oleeResourceRecordDocument.getOleEResourceVariantTitleList().size() != 1) {
1927                         isVariantTitleBlank = true;
1928                     }
1929                 }
1930             }
1931             if (isVariantTitleBlank) {
1932                 GlobalVariables.getMessageMap().putErrorForSectionId(OLEConstants.OLEEResourceRecord.VARIANT_TITLE_SECTION_ID, OLEConstants.OLEEResourceRecord.SHOULD_NOT_BLANK, new String[]{"Variant Title"});
1933                 flag = true;
1934             }
1935         }
1936         if (oleeResourceRecordDocument.getAccountingLines().size() > 0) {
1937             BigDecimal totalPercentage = BigDecimal.ZERO;
1938             BigDecimal desiredPercent = new BigDecimal("100");
1939             for (OLEEResourceAccountingLine accountingLine : oleeResourceRecordDocument.getAccountingLines()) {
1940                 if (validateAccountingLines(accountingLine, KRADConstants.GLOBAL_ERRORS)) {
1941                     flag = true;
1942                 }
1943                 totalPercentage = totalPercentage.add(accountingLine.getAccountLinePercent());
1944             }
1945             if (desiredPercent.compareTo(totalPercentage) != 0) {
1946                 GlobalVariables.getMessageMap().putErrorForSectionId(KRADConstants.GLOBAL_ERRORS, OLEConstants.OLEEResourceRecord.ERROR_PERCENTAGE_LESS_THAN_HUNDRED);
1947                 flag = true;
1948             }
1949         }
1950 
1951         return flag;
1952     }
1953 
1954     public void saveEResourceInstanceToDocstore(OLEEResourceRecordDocument oleeResourceRecordDocument) throws Exception {
1955         if (oleeResourceRecordDocument.getOleERSInstances() != null && oleeResourceRecordDocument.getOleERSInstances().size() != 0) {
1956             List<OLEEResourceInstance> oleeResourceInstanceList =oleeResourceRecordDocument.getOleERSInstances();
1957             List<OLEEResourceInstance> oleeResourceInstanceDletedList = new ArrayList<>();
1958             List<org.kuali.ole.docstore.common.document.HoldingsTree> holdingsTreeList = new ArrayList<>();
1959             for (OLEEResourceInstance oleeResourceInstance : oleeResourceInstanceList) {
1960                 if (oleeResourceInstance != null) {
1961                     if (org.apache.commons.lang.StringUtils.isBlank(oleeResourceInstance.getSubscriptionStatus())
1962                             && org.apache.commons.lang.StringUtils.isNotBlank(oleeResourceRecordDocument.getSubscriptionStatus()) ) {
1963                         oleeResourceInstance.setSubscriptionStatus(oleeResourceRecordDocument.getSubscriptionStatus());
1964                         oleeResourceRecordDocument.getOleERSInstancesForSave().add(oleeResourceInstance);
1965                     }
1966                     boolean isUpdate = false;
1967                     String eHoldingsId = oleeResourceInstance.getInstanceId();
1968                     if (StringUtils.isNotEmpty(eHoldingsId)) {
1969 
1970                         Holdings holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(eHoldingsId);
1971                         if (StringUtils.isNotEmpty(holdings.getId())) {
1972                             OleHoldings oleHoldings = (OleHoldings) holdings.deserializeContent(holdings.getContent());
1973 
1974                             if(oleHoldings != null) {
1975                                 if (StringUtils.isEmpty(oleHoldings.getEResourceId())) {
1976                                     oleHoldings.setEResourceId(oleeResourceRecordDocument.getOleERSIdentifier());
1977                                     isUpdate = true;
1978                                 }
1979                                 StatisticalSearchingCode statisticalSearchingCode = new StatisticalSearchingCode();
1980                                 if (oleeResourceRecordDocument.getOleStatisticalCode() != null) {
1981                                     statisticalSearchingCode.setCodeValue(oleeResourceRecordDocument.getOleStatisticalCode().getStatisticalSearchingCode());
1982                                 }
1983                                 if (oleHoldings.getStatisticalSearchingCode() == null &&  statisticalSearchingCode.getCodeValue() != null) {
1984                                     oleHoldings.setStatisticalSearchingCode(statisticalSearchingCode);
1985                                     isUpdate = true;
1986                                 }
1987                                 if (oleHoldings.getHoldingsAccessInformation() == null ) {
1988                                     oleHoldings.getHoldingsAccessInformation().setNumberOfSimultaneousUser(oleeResourceRecordDocument.getNumOfSimultaneousUsers());
1989                                     oleHoldings.getHoldingsAccessInformation().setAccessLocation(oleeResourceRecordDocument.getAccessLocationId());
1990                                     oleHoldings.getHoldingsAccessInformation().setAuthenticationType(oleeResourceRecordDocument.getOleAuthenticationType().getOleAuthenticationTypeName());
1991                                     isUpdate = true;
1992                                 }
1993                                 buildInstanceHolding(oleeResourceInstance, oleHoldings, oleeResourceRecordDocument);
1994                                 holdings.setContent(holdings.serializeContent(oleHoldings));
1995                                 if(isUpdate){
1996                                     HoldingsTree holdingsTree = new HoldingsTree();
1997                                     holdings.setOperation(DocstoreDocument.OperationType.UPDATE);
1998                                     holdingsTree.setHoldings(holdings);
1999                                     holdingsTreeList.add(holdingsTree);
2000                                 }
2001                             }
2002                         } else {
2003                             oleeResourceInstanceDletedList.add(oleeResourceInstance);
2004                         }
2005                         if (CollectionUtils.isNotEmpty(oleeResourceInstanceDletedList)) {
2006                             oleeResourceRecordDocument.getOleERSInstances().removeAll(oleeResourceInstanceDletedList);
2007                             oleeResourceRecordDocument.getOleERSInstancesForDelete().addAll(oleeResourceInstanceDletedList);
2008                         }
2009                     }
2010                 }
2011             }
2012 
2013             if (CollectionUtils.isNotEmpty(oleeResourceRecordDocument.getOleERSInstancesForSave())) {
2014                 getBusinessObjectService().save(oleeResourceRecordDocument.getOleERSInstancesForSave());
2015             }
2016 
2017 
2018             if(holdingsTreeList.size()  > 0) {
2019                 BibTrees bibTrees = new BibTrees();
2020                 BibTree bibTree = new BibTree();
2021                 bibTree.getHoldingsTrees().addAll(holdingsTreeList);
2022                 bibTrees.getBibTrees().add(bibTree);
2023                 getDocstoreClientLocator().getDocstoreClient().processBibTrees(bibTrees);
2024             }
2025         }
2026     }
2027 
2028     public boolean validateCoverageStartDates(OLEEResourceRecordDocument oleeResourceRecordDocument, OLEEResourceRecordForm oleERSForm) {
2029         boolean coverageStartFlag = true;
2030         OLEEResourceInstance oleeResourceInstance = oleeResourceRecordDocument.getOleERSInstance();
2031         oleERSForm.setDefaultCovStartDateErrorMessage(null);
2032         String coverageStartDate = "";
2033         try {
2034             if (oleeResourceInstance != null) {
2035                 coverageStartDate = oleeResourceInstance.getCovStartDate();
2036                 if (StringUtils.isNotEmpty(coverageStartDate)) {
2037                     if (coverageStartDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2038                         //String dateFormat = getDateFormat(coverageStartDate);
2039                         String dateFormat = coverageStartDate;
2040                         oleeResourceInstance.setCovStartDate(dateFormat);
2041                     } else if (coverageStartDate.matches(calendarYearAgo)) {
2042                         String[] coverageStartYear = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2043                         if (coverageStartYear.length > 0 && coverageStartYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2044                             /*String previousYearOfCovDate = getYearFormat();
2045                             previousYearOfCovDate = getFirstDay(previousYearOfCovDate);*/
2046                             String previousYearOfCovDate = coverageStartDate;
2047                             oleeResourceInstance.setCovStartDate(previousYearOfCovDate);
2048                         } else {
2049                             coverageStartFlag = false;
2050                             oleERSForm.setCoverageFlag(true);
2051                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2052                         }
2053                     } else if (coverageStartDate.matches(calendarYearsAgo)) {
2054                         String[] coverageStartYears = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2055                         if (coverageStartYears.length > 0 && !coverageStartYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2056                             /*String previousYearsOfCovDate = getYearsFormat(coverageStartYears);
2057                             previousYearsOfCovDate = getFirstDay(previousYearsOfCovDate);*/
2058                             String previousYearsOfCovDate = coverageStartDate;
2059                             oleeResourceInstance.setCovStartDate(previousYearsOfCovDate);
2060                         } else {
2061                             coverageStartFlag = false;
2062                             oleERSForm.setCoverageFlag(true);
2063                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2064                         }
2065                     } else if (coverageStartDate.matches(monthAgo)) {
2066                         String[] coverageStartMonth = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2067                         if (coverageStartMonth.length > 0 && coverageStartMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2068                             //String previousMonthOfCovDate = getMonthFormat();
2069                             String previousMonthOfCovDate = coverageStartDate;
2070                             oleeResourceInstance.setCovStartDate(previousMonthOfCovDate);
2071                         } else {
2072                             coverageStartFlag = false;
2073                             oleERSForm.setCoverageFlag(true);
2074                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2075                         }
2076                     } else if (coverageStartDate.matches(monthsAgo)) {
2077                         String[] coverageStartMonths = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2078                         if (coverageStartMonths.length > 0 && !coverageStartMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2079                             //String previousMonthsOfCovDate = getMonthsFormat(coverageStartMonths);
2080                             String previousMonthsOfCovDate = coverageStartDate;
2081                             oleeResourceInstance.setCovStartDate(previousMonthsOfCovDate);
2082                         } else {
2083                             coverageStartFlag = false;
2084                             oleERSForm.setCoverageFlag(true);
2085                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2086                         }
2087                     } else if (coverageStartDate.matches(weekAgo)) {
2088                         String[] coverageStartWeek = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2089                         if (coverageStartWeek.length > 0 && coverageStartWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2090                             //String previousWeekOfCovDate = getWeekFormat();
2091                             String previousWeekOfCovDate = coverageStartDate;
2092                             oleeResourceInstance.setCovStartDate(previousWeekOfCovDate);
2093                         } else {
2094                             coverageStartFlag = false;
2095                             oleERSForm.setCoverageFlag(true);
2096                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2097                         }
2098                     } else if (coverageStartDate.matches(weeksAgo)) {
2099                         String[] coverageStartWeeks = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2100                         if (coverageStartWeeks.length > 0 && !coverageStartWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2101                             //String previousYearsOfCovDate = getWeeksFormat(coverageStartWeeks);
2102                             String previousYearsOfCovDate = coverageStartDate;
2103                             oleeResourceInstance.setCovStartDate(previousYearsOfCovDate);
2104                         } else {
2105                             coverageStartFlag = false;
2106                             oleERSForm.setCoverageFlag(true);
2107                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2108                         }
2109                     } else if (coverageStartDate.matches(dayAgo)) {
2110                         String[] coverageStartDay = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2111                         if (coverageStartDay.length > 0 && coverageStartDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2112                             //String previousDayOfCovDate = getDayFormat();
2113                             String previousDayOfCovDate = coverageStartDate;
2114                             oleeResourceInstance.setCovStartDate(previousDayOfCovDate);
2115                         } else {
2116                             coverageStartFlag = false;
2117                             oleERSForm.setCoverageFlag(true);
2118                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2119                         }
2120                     } else if (coverageStartDate.matches(daysAgo)) {
2121                         String[] coverageStartDays = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2122                         if (coverageStartDays.length > 0 && !coverageStartDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2123                             //String previousDaysOfCovDate = getDaysFormat(coverageStartDays);
2124                             String previousDaysOfCovDate = coverageStartDate;
2125                             oleeResourceInstance.setCovStartDate(previousDaysOfCovDate);
2126                         } else {
2127                             coverageStartFlag = false;
2128                             oleERSForm.setCoverageFlag(true);
2129                             oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2130                         }
2131                     } else {
2132                         coverageStartFlag = false;
2133                         oleERSForm.setCoverageFlag(true);
2134                         oleERSForm.setDefaultCovStartDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_START_DATE_FORMAT_INV);
2135                     }
2136                 }
2137             }
2138             oleeResourceRecordDocument.setCovStartDate(coverageStartDate);
2139         } catch (Exception ex) {
2140             LOG.error("Exception while validating the coverage start date format in EResource" + ex.getMessage());
2141             throw new RuntimeException();
2142         }
2143         return coverageStartFlag;
2144     }
2145 
2146     public boolean validateCoverageEndDates(OLEEResourceRecordDocument oleeResourceRecordDocument, OLEEResourceRecordForm oleERSForm) {
2147         boolean coverageEndFlag = true;
2148         OLEEResourceInstance oleeResourceInstance = oleeResourceRecordDocument.getOleERSInstance();
2149         oleERSForm.setDefaultCovEndDateErrorMessage(null);
2150         String coverageEndDate = "";
2151         try {
2152             if (oleeResourceInstance != null) {
2153                 coverageEndDate = oleeResourceInstance.getCovEndDate();
2154                 if (StringUtils.isNotEmpty(coverageEndDate)) {
2155                     if (coverageEndDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2156                         //String dateFormat = getDateFormat(coverageEndDate);
2157                         String dateFormat = coverageEndDate;
2158                         oleeResourceInstance.setCovEndDate(dateFormat);
2159                     } else if (coverageEndDate.matches(calendarYearAgo)) {
2160                         String[] coverageEndYear = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2161                         if (coverageEndYear.length > 0 && coverageEndYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2162                             /*String previousYearOfCovDate = getYearFormat();
2163                             previousYearOfCovDate = getLastDay(previousYearOfCovDate);*/
2164                             String previousYearOfCovDate = coverageEndDate;
2165                             oleeResourceInstance.setCovEndDate(previousYearOfCovDate);
2166                         } else {
2167                             coverageEndFlag = false;
2168                             oleERSForm.setCoverageFlag(true);
2169                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2170                         }
2171                     } else if (coverageEndDate.matches(calendarYearsAgo)) {
2172                         String[] coverageEndYears = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2173                         if (coverageEndYears.length > 0 && !coverageEndYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2174                             /*String previousYearsOfCovDate = getYearsFormat(coverageEndYears);
2175                             previousYearsOfCovDate = getLastDay(previousYearsOfCovDate);*/
2176                             String previousYearsOfCovDate = coverageEndDate;
2177                             oleeResourceInstance.setCovEndDate(previousYearsOfCovDate);
2178                         } else {
2179                             coverageEndFlag = false;
2180                             oleERSForm.setCoverageFlag(true);
2181                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2182                         }
2183                     } else if (coverageEndDate.matches(monthAgo)) {
2184                         String[] coverageEndMonth = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2185                         if (coverageEndMonth.length > 0 && coverageEndMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2186                             //String previousMonthOfCovDate = getMonthFormat();
2187                             String previousMonthOfCovDate = coverageEndDate;
2188                             oleeResourceInstance.setCovEndDate(previousMonthOfCovDate);
2189                         } else {
2190                             coverageEndFlag = false;
2191                             oleERSForm.setCoverageFlag(true);
2192                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2193                         }
2194                     } else if (coverageEndDate.matches(monthsAgo)) {
2195                         String[] coverageEndMonths = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2196                         if (coverageEndMonths.length > 0 && !coverageEndMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2197                             //String previousMonthsOfCovDate = getMonthsFormat(coverageEndMonths);
2198                             String previousMonthsOfCovDate = coverageEndDate;
2199                             oleeResourceInstance.setCovEndDate(previousMonthsOfCovDate);
2200                         } else {
2201                             coverageEndFlag = false;
2202                             oleERSForm.setCoverageFlag(true);
2203                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2204                         }
2205                     } else if (coverageEndDate.matches(weekAgo)) {
2206                         String[] coverageEndWeek = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2207                         if (coverageEndWeek.length > 0 && coverageEndWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2208                             //String previousWeekOfCovEndDate = getWeekFormat();
2209                             String previousWeekOfCovEndDate = coverageEndDate;
2210                             oleeResourceInstance.setCovEndDate(previousWeekOfCovEndDate);
2211                         } else {
2212                             coverageEndFlag = false;
2213                             oleERSForm.setCoverageFlag(true);
2214                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2215                         }
2216                     } else if (coverageEndDate.matches(weeksAgo)) {
2217                         String[] coverageEndWeeks = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2218                         if (coverageEndWeeks.length > 0 && !coverageEndWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2219                             //String previousWeeksOfCovEndDate = getWeeksFormat(coverageEndWeeks);
2220                             String previousWeeksOfCovEndDate = coverageEndDate;
2221                             oleeResourceInstance.setCovEndDate(previousWeeksOfCovEndDate);
2222                         } else {
2223                             coverageEndFlag = false;
2224                             oleERSForm.setCoverageFlag(true);
2225                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2226                         }
2227                     } else if (coverageEndDate.matches(dayAgo)) {
2228                         String[] coverageEndDay = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2229                         if (coverageEndDay.length > 0 && coverageEndDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2230                             //String previousDayOfCovDate = getDayFormat();
2231                             String previousDayOfCovDate = coverageEndDate;
2232                             oleeResourceInstance.setCovEndDate(previousDayOfCovDate);
2233                         } else {
2234                             coverageEndFlag = false;
2235                             oleERSForm.setCoverageFlag(true);
2236                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2237                         }
2238                     } else if (coverageEndDate.matches(daysAgo)) {
2239                         String[] coverageEndDays = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2240                         if (coverageEndDays.length > 0 && !coverageEndDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2241                             //String previousDaysOfCovEndDate = getDaysFormat(coverageEndDays);
2242                             String previousDaysOfCovEndDate = coverageEndDate;
2243                             oleeResourceInstance.setCovEndDate(previousDaysOfCovEndDate);
2244                         } else {
2245                             coverageEndFlag = false;
2246                             oleERSForm.setCoverageFlag(true);
2247                             oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2248                         }
2249                     } else {
2250                         coverageEndFlag = false;
2251                         oleERSForm.setCoverageFlag(true);
2252                         oleERSForm.setDefaultCovEndDateErrorMessage(OLEConstants.OLEEResourceRecord.COV_END_DATE_FORMAT_INV);
2253                     }
2254                 }
2255             }
2256             oleeResourceRecordDocument.setCovEndDate(coverageEndDate);
2257         } catch (Exception ex) {
2258             LOG.error("Exception while validating the coverage end date format in EResource" + ex.getMessage());
2259             throw new RuntimeException();
2260         }
2261         return coverageEndFlag;
2262     }
2263 
2264     public boolean validatePerpetualAccessStartDates(OLEEResourceRecordDocument oleeResourceRecordDocument, OLEEResourceRecordForm oleERSForm) {
2265         boolean perpetualAccessStartFlag = true;
2266         OLEEResourceInstance oleeResourceInstance = oleeResourceRecordDocument.getOleERSInstance();
2267         oleERSForm.setDefaultPerAccStartDateErrorMessage(null);
2268         String perpetualAccessStartDate = "";
2269         try {
2270             if (oleeResourceInstance != null) {
2271                 perpetualAccessStartDate = oleeResourceInstance.getPerpetualAccStartDate();
2272                 if (StringUtils.isNotEmpty(perpetualAccessStartDate)) {
2273                     if (perpetualAccessStartDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2274                         //String dateFormat = getDateFormat(perpetualAccessStartDate);
2275                         String dateFormat = perpetualAccessStartDate;
2276                         oleeResourceInstance.setPerpetualAccStartDate(dateFormat);
2277                     } else if (perpetualAccessStartDate.matches(calendarYearAgo)) {
2278                         String[] perpetualAccessStartYear = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2279                         if (perpetualAccessStartYear.length > 0 && perpetualAccessStartYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2280                             /*String previousYearOfPerpetualAccDate = getYearFormat();
2281                             previousYearOfPerpetualAccDate = getFirstDay(previousYearOfPerpetualAccDate);*/
2282                             String previousYearOfPerpetualAccDate = perpetualAccessStartDate;
2283                             oleeResourceInstance.setPerpetualAccStartDate(previousYearOfPerpetualAccDate);
2284                         } else {
2285                             perpetualAccessStartFlag = false;
2286                             oleERSForm.setPerpetualAccessFlag(true);
2287                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2288                         }
2289                     } else if (perpetualAccessStartDate.matches(calendarYearsAgo)) {
2290                         String[] perpetualAccessStartYears = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2291                         if (perpetualAccessStartYears.length > 0 && !perpetualAccessStartYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2292                             /*String previousYearsOfPerpetualAccDate = getYearsFormat(perpetualAccessStartYears);
2293                             previousYearsOfPerpetualAccDate = getFirstDay(previousYearsOfPerpetualAccDate);*/
2294                             String previousYearsOfPerpetualAccDate = perpetualAccessStartDate;
2295                             oleeResourceInstance.setPerpetualAccStartDate(previousYearsOfPerpetualAccDate);
2296                         } else {
2297                             perpetualAccessStartFlag = false;
2298                             oleERSForm.setPerpetualAccessFlag(true);
2299                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2300                         }
2301                     } else if (perpetualAccessStartDate.matches(monthAgo)) {
2302                         String[] perpetualAccessStartMonth = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2303                         if (perpetualAccessStartMonth.length > 0 && perpetualAccessStartMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2304                             //String previousMonthOfPerpetualAccDate = getMonthFormat();
2305                             String previousMonthOfPerpetualAccDate = perpetualAccessStartDate;
2306                             oleeResourceInstance.setPerpetualAccStartDate(previousMonthOfPerpetualAccDate);
2307                         } else {
2308                             perpetualAccessStartFlag = false;
2309                             oleERSForm.setPerpetualAccessFlag(true);
2310                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2311                         }
2312                     } else if (perpetualAccessStartDate.matches(monthsAgo)) {
2313                         String[] perpetualAccessStartMonths = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2314                         if (perpetualAccessStartMonths.length > 0 && !perpetualAccessStartMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2315                             //String previousMonthsOfPerpetualAccDate = getMonthsFormat(perpetualAccessStartMonths);
2316                             String previousMonthsOfPerpetualAccDate = perpetualAccessStartDate;
2317                             oleeResourceInstance.setPerpetualAccStartDate(previousMonthsOfPerpetualAccDate);
2318                         } else {
2319                             perpetualAccessStartFlag = false;
2320                             oleERSForm.setPerpetualAccessFlag(true);
2321                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2322                         }
2323                     } else if (perpetualAccessStartDate.matches(weekAgo)) {
2324                         String[] perpetualAccessStartWeek = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2325                         if (perpetualAccessStartWeek.length > 0 && perpetualAccessStartWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2326                             //String previousWeekOfCovEndDate = getWeekFormat();
2327                             String previousWeekOfCovEndDate = perpetualAccessStartDate;
2328                             oleeResourceInstance.setPerpetualAccStartDate(previousWeekOfCovEndDate);
2329                         } else {
2330                             perpetualAccessStartFlag = false;
2331                             oleERSForm.setPerpetualAccessFlag(true);
2332                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2333                         }
2334                     } else if (perpetualAccessStartDate.matches(weeksAgo)) {
2335                         String[] perpetualAccessStartWeeks = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2336                         if (perpetualAccessStartWeeks.length > 0 && !perpetualAccessStartWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2337                             //String previousWeeksOfCovEndDate = getWeeksFormat(perpetualAccessStartWeeks);
2338                             String previousWeeksOfCovEndDate = perpetualAccessStartDate;
2339                             oleeResourceInstance.setPerpetualAccStartDate(previousWeeksOfCovEndDate);
2340                         } else {
2341                             perpetualAccessStartFlag = false;
2342                             oleERSForm.setPerpetualAccessFlag(true);
2343                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2344                         }
2345                     } else if (perpetualAccessStartDate.matches(dayAgo)) {
2346                         String[] perpetualAccessStartDay = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2347                         if (perpetualAccessStartDay.length > 0 && perpetualAccessStartDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2348                             //String previousDayOfPerpetualAccDate = getDayFormat();
2349                             String previousDayOfPerpetualAccDate = perpetualAccessStartDate;
2350                             oleeResourceInstance.setPerpetualAccStartDate(previousDayOfPerpetualAccDate);
2351                         } else {
2352                             perpetualAccessStartFlag = false;
2353                             oleERSForm.setPerpetualAccessFlag(true);
2354                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2355                         }
2356                     } else if (perpetualAccessStartDate.matches(daysAgo)) {
2357                         String[] perpetualAccessStartDays = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2358                         if (perpetualAccessStartDays.length > 0 && !perpetualAccessStartDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2359                             //String previousDaysOfPerpetualAccDate = getDaysFormat(perpetualAccessStartDays);
2360                             String previousDaysOfPerpetualAccDate = perpetualAccessStartDate;
2361                             oleeResourceInstance.setPerpetualAccStartDate(previousDaysOfPerpetualAccDate);
2362                         } else {
2363                             perpetualAccessStartFlag = false;
2364                             oleERSForm.setPerpetualAccessFlag(true);
2365                             oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2366                         }
2367                     } else {
2368                         perpetualAccessStartFlag = false;
2369                         oleERSForm.setDefaultPerAccStartDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_START_DATE_FORMAT_INV);
2370                     }
2371                 }
2372             }
2373             oleeResourceRecordDocument.setPerAccStartDate(perpetualAccessStartDate);
2374         } catch (Exception ex) {
2375             LOG.error("Exception while validating the perpetual access start date format in EResource" + ex.getMessage());
2376             throw new RuntimeException();
2377         }
2378         return perpetualAccessStartFlag;
2379     }
2380 
2381     public boolean validatePerpetualAccessEndDates(OLEEResourceRecordDocument oleeResourceRecordDocument, OLEEResourceRecordForm oleERSForm) {
2382         boolean perpetualAccessEndFlag = true;
2383         OLEEResourceInstance oleeResourceInstance = oleeResourceRecordDocument.getOleERSInstance();
2384         oleERSForm.setDefaultPerAccEndDateErrorMessage(null);
2385         String perpetualAccessEndDate = "";
2386         try {
2387             if (oleeResourceInstance != null) {
2388                 perpetualAccessEndDate = oleeResourceInstance.getPerpetualAccEndDate();
2389                 if (StringUtils.isNotEmpty(perpetualAccessEndDate)) {
2390                     if (perpetualAccessEndDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2391                         //String dateFormat = getDateFormat(perpetualAccessEndDate);
2392                         String dateFormat = perpetualAccessEndDate;
2393                         oleeResourceInstance.setPerpetualAccEndDate(dateFormat);
2394                     } else if (perpetualAccessEndDate.matches(calendarYearAgo)) {
2395                         String[] perpetualAccessEndYear = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2396                         if (perpetualAccessEndYear.length > 0 && perpetualAccessEndYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2397                            /* String previousYearOfPerpetualAccDate = getYearFormat();
2398                             previousYearOfPerpetualAccDate = getLastDay(previousYearOfPerpetualAccDate);*/
2399                             String previousYearOfPerpetualAccDate = perpetualAccessEndDate;
2400                             oleeResourceInstance.setPerpetualAccEndDate(previousYearOfPerpetualAccDate);
2401                         } else {
2402                             perpetualAccessEndFlag = false;
2403                             oleERSForm.setPerpetualAccessFlag(true);
2404                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2405                         }
2406                     } else if (perpetualAccessEndDate.matches(calendarYearsAgo)) {
2407                         String[] perpetualAccessEndYears = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2408                         if (perpetualAccessEndYears.length > 0 && !perpetualAccessEndYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2409                             /*String previousYearsOfPerpetualAccDate = getYearsFormat(perpetualAccessEndYears);
2410                             previousYearsOfPerpetualAccDate = getLastDay(previousYearsOfPerpetualAccDate);*/
2411                             String previousYearsOfPerpetualAccDate = perpetualAccessEndDate;
2412                             oleeResourceInstance.setPerpetualAccEndDate(previousYearsOfPerpetualAccDate);
2413                         } else {
2414                             perpetualAccessEndFlag = false;
2415                             oleERSForm.setPerpetualAccessFlag(true);
2416                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2417                         }
2418                     } else if (perpetualAccessEndDate.matches(monthAgo)) {
2419                         String[] perpetualAccessEndMonth = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2420                         if (perpetualAccessEndMonth.length > 0 && perpetualAccessEndMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2421                             //String previousMonthOfPerpetualAccDate = getMonthFormat();
2422                             String previousMonthOfPerpetualAccDate = perpetualAccessEndDate;
2423                             oleeResourceInstance.setPerpetualAccEndDate(previousMonthOfPerpetualAccDate);
2424                         } else {
2425                             perpetualAccessEndFlag = false;
2426                             oleERSForm.setPerpetualAccessFlag(true);
2427                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2428                         }
2429                     } else if (perpetualAccessEndDate.matches(monthsAgo)) {
2430                         String[] perpetualAccessEndMonths = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2431                         if (perpetualAccessEndMonths.length > 0 && !perpetualAccessEndMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2432                             //String previousMonthsOfPerpetualAccDate = getMonthsFormat(perpetualAccessEndMonths);
2433                             String previousMonthsOfPerpetualAccDate = perpetualAccessEndDate;
2434                             oleeResourceInstance.setPerpetualAccEndDate(previousMonthsOfPerpetualAccDate);
2435                         } else {
2436                             perpetualAccessEndFlag = false;
2437                             oleERSForm.setPerpetualAccessFlag(true);
2438                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2439                         }
2440                     } else if (perpetualAccessEndDate.matches(weekAgo)) {
2441                         String[] perpetualAccessEndWeek = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2442                         if (perpetualAccessEndWeek.length > 0 && !perpetualAccessEndWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2443                             //String previousWeekOfPerpetualAccDate = getWeekFormat();
2444                             String previousWeekOfPerpetualAccDate = perpetualAccessEndDate;
2445                             oleeResourceInstance.setPerpetualAccEndDate(previousWeekOfPerpetualAccDate);
2446                         } else {
2447                             perpetualAccessEndFlag = false;
2448                             oleERSForm.setPerpetualAccessFlag(true);
2449                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2450                         }
2451                     } else if (perpetualAccessEndDate.matches(weeksAgo)) {
2452                         String[] perpetualAccessEndWeeks = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2453                         if (perpetualAccessEndWeeks.length > 0 && !perpetualAccessEndWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2454                             //String previousWeeksOfPerpetualAccDate = getWeeksFormat(perpetualAccessEndWeeks);
2455                             String previousWeeksOfPerpetualAccDate = perpetualAccessEndDate;
2456                             oleeResourceInstance.setPerpetualAccEndDate(previousWeeksOfPerpetualAccDate);
2457                         } else {
2458                             perpetualAccessEndFlag = false;
2459                             oleERSForm.setPerpetualAccessFlag(true);
2460                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2461                         }
2462                     } else if (perpetualAccessEndDate.matches(dayAgo)) {
2463                         String[] perpetualAccessEndDay = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2464                         if (perpetualAccessEndDay.length > 0 && perpetualAccessEndDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2465                             //String previousDayOfPerpetualAccDate = getDayFormat();
2466                             String previousDayOfPerpetualAccDate = perpetualAccessEndDate;
2467                             oleeResourceInstance.setPerpetualAccEndDate(previousDayOfPerpetualAccDate);
2468                         } else {
2469                             perpetualAccessEndFlag = false;
2470                             oleERSForm.setPerpetualAccessFlag(true);
2471                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2472                         }
2473                     } else if (perpetualAccessEndDate.matches(daysAgo)) {
2474                         String[] perpetualAccessEndDays = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2475                         if (perpetualAccessEndDays.length > 0 && !perpetualAccessEndDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2476                             //String previousDaysOfPerpetualAccDate = getDaysFormat(perpetualAccessEndDays);
2477                             String previousDaysOfPerpetualAccDate = perpetualAccessEndDate;
2478                             oleeResourceInstance.setPerpetualAccEndDate(previousDaysOfPerpetualAccDate);
2479                         } else {
2480                             perpetualAccessEndFlag = false;
2481                             oleERSForm.setPerpetualAccessFlag(true);
2482                             oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2483                         }
2484                     } else {
2485                         perpetualAccessEndFlag = false;
2486                         oleERSForm.setDefaultPerAccEndDateErrorMessage(OLEConstants.OLEEResourceRecord.PER_ACC_END_DATE_FORMAT_INV);
2487                     }
2488                 }
2489             }
2490             oleeResourceRecordDocument.setPerAccEndDate(perpetualAccessEndDate);
2491         } catch (Exception ex) {
2492             LOG.error("Exception while validating the perpetual access end date format in EResource" + ex.getMessage());
2493             throw new RuntimeException();
2494         }
2495         return perpetualAccessEndFlag;
2496     }
2497 
2498     public boolean validateDates(OleHoldings eHoldings) {
2499         boolean dateFlag = true;
2500         dateFlag &= validateCoverageStartDateForEHolding(eHoldings);
2501         dateFlag &= validateCoverageEndDateForEHolding(eHoldings);
2502         dateFlag &= validatePerpetualAccStartDateForEHolding(eHoldings);
2503         dateFlag &= validatePerpetualAccEndDateForEHolding(eHoldings);
2504         return dateFlag;
2505     }
2506 
2507     public boolean validateCoverageStartDateForEHolding(OleHoldings eHoldings) {
2508         boolean covStartDateFlag = true;
2509         List<Coverage> coverageList = new ArrayList<>();
2510         if (eHoldings.getExtentOfOwnership().size() > 0 && eHoldings.getExtentOfOwnership().get(0).getCoverages() != null
2511                 && eHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage().size() > 0) {
2512             coverageList = eHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage();
2513             for (Coverage coverage : coverageList) {
2514                 if(StringUtils.isNotEmpty(coverage.getCoverageStartDateString())) {
2515                     coverage.setCoverageStartDate(coverage.getCoverageStartDateString());
2516                 } else if(StringUtils.isNotEmpty(coverage.getCoverageStartDateFormat())) {
2517                     coverage.setCoverageStartDate(coverage.getCoverageStartDateFormat());
2518                 }
2519                 covStartDateFlag &= validateCoverageStartDates(coverage);
2520             }
2521             if (!covStartDateFlag) {
2522                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleHoldings.ERROR_MSG_COV_START_DATE);
2523                 return covStartDateFlag;
2524             }
2525         }
2526         return covStartDateFlag;
2527     }
2528 
2529     public boolean validateCoverageEndDateForEHolding(OleHoldings eHoldings) {
2530         boolean covEndDateFlag = true;
2531         List<Coverage> coverageList = new ArrayList<>();
2532         if (eHoldings.getExtentOfOwnership().size() > 0 && eHoldings.getExtentOfOwnership().get(0).getCoverages() != null
2533                 && eHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage().size() > 0) {
2534             coverageList = eHoldings.getExtentOfOwnership().get(0).getCoverages().getCoverage();
2535             for (Coverage coverage : coverageList) {
2536                 if(StringUtils.isNotEmpty(coverage.getCoverageEndDateString())) {
2537                     coverage.setCoverageEndDate(coverage.getCoverageEndDateString());
2538                 } else if(StringUtils.isNotEmpty(coverage.getCoverageEndDateFormat())) {
2539                     coverage.setCoverageEndDate(coverage.getCoverageEndDateFormat());
2540                 }
2541                 covEndDateFlag &= validateCoverageEndDates(coverage);
2542             }
2543             if (!covEndDateFlag) {
2544                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleHoldings.ERROR_MSG_COV_END_DATE);
2545                 return covEndDateFlag;
2546             }
2547         }
2548         return covEndDateFlag;
2549     }
2550 
2551     public boolean validatePerpetualAccStartDateForEHolding(OleHoldings eHoldings) {
2552         boolean perpetualAccStartDateFlag = true;
2553         List<PerpetualAccess> perpetualAccessList = new ArrayList<>();
2554         if (eHoldings.getExtentOfOwnership().size() > 0 && eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses() != null
2555                 && eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses().getPerpetualAccess().size() > 0) {
2556             perpetualAccessList = eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses().getPerpetualAccess();
2557             for (PerpetualAccess perpetualAccess : perpetualAccessList) {
2558                 if(StringUtils.isNotEmpty(perpetualAccess.getPerpetualAccessStartDateFormat())) {
2559                     perpetualAccess.setPerpetualAccessStartDate(perpetualAccess.getPerpetualAccessStartDateFormat());
2560                 } else if(StringUtils.isNotEmpty(perpetualAccess.getPerpetualAccessStartDateString())) {
2561                     perpetualAccess.setPerpetualAccessStartDate(perpetualAccess.getPerpetualAccessStartDateString());
2562                 }
2563                 perpetualAccStartDateFlag &= validatePerpetualAccessStartDates(perpetualAccess);
2564             }
2565             if (!perpetualAccStartDateFlag) {
2566                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleHoldings.ERROR_MSG_PER_ACC_START_DATE);
2567                 return perpetualAccStartDateFlag;
2568             }
2569         }
2570         return perpetualAccStartDateFlag;
2571     }
2572 
2573     public boolean validatePerpetualAccEndDateForEHolding(OleHoldings eHoldings) {
2574         boolean perpetualAccEndDateFlag = true;
2575         List<PerpetualAccess> perpetualAccessList = new ArrayList<>();
2576         if (eHoldings.getExtentOfOwnership().size() > 0 && eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses() != null
2577                 && eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses().getPerpetualAccess().size() > 0) {
2578             perpetualAccessList = eHoldings.getExtentOfOwnership().get(0).getPerpetualAccesses().getPerpetualAccess();
2579             for (PerpetualAccess perpetualAccess : perpetualAccessList) {
2580                 if(StringUtils.isNotEmpty(perpetualAccess.getPerpetualAccessEndDateString())) {
2581                     perpetualAccess.setPerpetualAccessEndDate(perpetualAccess.getPerpetualAccessEndDateString());
2582                 } else if(StringUtils.isNotEmpty(perpetualAccess.getPerpetualAccessEndDateFormat())) {
2583                     perpetualAccess.setPerpetualAccessEndDate(perpetualAccess.getPerpetualAccessEndDateFormat());
2584                 }
2585                 perpetualAccEndDateFlag &= validatePerpetualAccessEndDates(perpetualAccess);
2586             }
2587             if (!perpetualAccEndDateFlag) {
2588                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleHoldings.ERROR_MSG_PER_ACC_END_DATE);
2589                 return perpetualAccEndDateFlag;
2590             }
2591         }
2592         return perpetualAccEndDateFlag;
2593     }
2594 
2595     private boolean validateCoverageStartDates(Coverage coverage) {
2596         boolean coverageStartFlag = true;
2597         String coverageStartDate = "";
2598         try {
2599             if (coverage != null) {
2600                 coverageStartDate = coverage.getCoverageStartDate();
2601                 if (StringUtils.isNotEmpty(coverageStartDate)) {
2602                     if (coverageStartDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2603                         //String dateFormat = getDateFormat(coverageStartDate);
2604                         String dateFormat = coverageStartDate;
2605                         coverage.setCoverageStartDate(dateFormat);
2606                     } else if (coverageStartDate.matches(calendarYearAgo)) {
2607                         String[] coverageStartYear = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2608                         if (coverageStartYear.length > 0 && coverageStartYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2609                             /*String previousYearOfCovDate = getYearFormat();
2610                             previousYearOfCovDate = getFirstDay(previousYearOfCovDate);*/
2611                             String previousYearOfCovDate = coverageStartDate;
2612                             coverage.setCoverageStartDate(previousYearOfCovDate);
2613                         } else {
2614                             coverage.setCoverageStartDate(coverageStartDate);
2615                             coverageStartFlag = false;
2616                         }
2617                     } else if (coverageStartDate.matches(calendarYearsAgo)) {
2618                         String[] coverageStartYears = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2619                         if (coverageStartYears.length > 0 && !coverageStartYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2620                             /*String previousYearsOfCovDate = getYearsFormat(coverageStartYears);
2621                             previousYearsOfCovDate = getFirstDay(previousYearsOfCovDate);*/
2622                             String previousYearsOfCovDate = coverageStartDate;
2623                             coverage.setCoverageStartDate(previousYearsOfCovDate);
2624                         } else {
2625                             coverageStartFlag = false;
2626                         }
2627                     } else if (coverageStartDate.matches(monthAgo)) {
2628                         String[] coverageStartMonth = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2629                         if (coverageStartMonth.length > 0 && coverageStartMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2630                             //String previousMonthOfCovDate = getMonthFormat();
2631                             String previousMonthOfCovDate = coverageStartDate;
2632                             coverage.setCoverageStartDate(previousMonthOfCovDate);
2633                         } else {
2634                             coverageStartFlag = false;
2635                         }
2636                     } else if (coverageStartDate.matches(monthsAgo)) {
2637                         String[] coverageStartMonths = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2638                         if (coverageStartMonths.length > 0 && !coverageStartMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2639                             //String previousMonthsOfCovDate = getMonthsFormat(coverageStartMonths);
2640                             String previousMonthsOfCovDate = coverageStartDate;
2641                             coverage.setCoverageStartDate(previousMonthsOfCovDate);
2642                         } else {
2643                             coverageStartFlag = false;
2644                         }
2645                     } else if (coverageStartDate.matches(weekAgo)) {
2646                         String[] coverageStartWeek = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2647                         if (coverageStartWeek.length > 0 && coverageStartWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2648                             //String previousWeekOfCovDate = getWeekFormat();
2649                             String previousWeekOfCovDate = coverageStartDate;
2650                             coverage.setCoverageStartDate(previousWeekOfCovDate);
2651                         } else {
2652                             coverageStartFlag = false;
2653                         }
2654                     } else if (coverageStartDate.matches(weeksAgo)) {
2655                         String[] coverageStartWeeks = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2656                         if (coverageStartWeeks.length > 0 && !coverageStartWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2657                             //String previousYearsOfCovDate = getWeeksFormat(coverageStartWeeks);
2658                             String previousYearsOfCovDate = coverageStartDate;
2659                             coverage.setCoverageStartDate(previousYearsOfCovDate);
2660                         } else {
2661                             coverageStartFlag = false;
2662                         }
2663                     } else if (coverageStartDate.matches(dayAgo)) {
2664                         String[] coverageStartDay = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2665                         if (coverageStartDay.length > 0 && coverageStartDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2666                             //String previousDayOfCovDate = getDayFormat();
2667                             String previousDayOfCovDate = coverageStartDate;
2668                             coverage.setCoverageStartDate(previousDayOfCovDate);
2669                         } else {
2670                             coverageStartFlag = false;
2671                         }
2672                     } else if (coverageStartDate.matches(daysAgo)) {
2673                         String[] coverageStartDays = coverageStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2674                         if (coverageStartDays.length > 0 && !coverageStartDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2675                             //String previousDaysOfCovDate = getDaysFormat(coverageStartDays);
2676                             String previousDaysOfCovDate = coverageStartDate;
2677                             coverage.setCoverageStartDate(previousDaysOfCovDate);
2678                         } else {
2679                             coverageStartFlag = false;
2680                         }
2681                     } else {
2682                         coverage.setCoverageStartDate(coverageStartDate);
2683                         coverageStartFlag = false;
2684                     }
2685                 }
2686             }
2687         } catch (Exception ex) {
2688             LOG.error("Exception while validating the coverage start date format in EHoldings" + ex.getMessage());
2689             throw new RuntimeException();
2690         }
2691         return coverageStartFlag;
2692     }
2693 
2694     private boolean validateCoverageEndDates(Coverage coverage) {
2695         boolean coverageEndFlag = true;
2696         String coverageEndDate = "";
2697         try {
2698             if (coverage != null) {
2699                 coverageEndDate = coverage.getCoverageEndDate();
2700                 if (StringUtils.isNotEmpty(coverageEndDate)) {
2701                     if (coverageEndDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2702                         //String dateFormat = getDateFormat(coverageEndDate);
2703                         String dateFormat = coverageEndDate;
2704                         coverage.setCoverageEndDate(dateFormat);
2705                     } else if (coverageEndDate.matches(calendarYearAgo)) {
2706                         String[] coverageEndYear = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2707                         if (coverageEndYear.length > 0 && coverageEndYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2708                             /*String previousYearOfCovDate = getYearFormat();
2709                             previousYearOfCovDate = getLastDay(previousYearOfCovDate);*/
2710                             String previousYearOfCovDate = coverageEndDate;
2711                             coverage.setCoverageEndDate(previousYearOfCovDate);
2712                         } else {
2713                             coverageEndFlag = false;
2714                         }
2715                     } else if (coverageEndDate.matches(calendarYearsAgo)) {
2716                         String[] coverageEndYears = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2717                         if (coverageEndYears.length > 0 && !coverageEndYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2718                             /*String previousYearsOfCovDate = getYearsFormat(coverageEndYears);
2719                             previousYearsOfCovDate = getLastDay(previousYearsOfCovDate);*/
2720                             String previousYearsOfCovDate = coverageEndDate;
2721                             coverage.setCoverageEndDate(previousYearsOfCovDate);
2722                         } else {
2723                             coverageEndFlag = false;
2724                         }
2725                     } else if (coverageEndDate.matches(monthAgo)) {
2726                         String[] coverageEndMonth = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2727                         if (coverageEndMonth.length > 0 && coverageEndMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2728                             //String previousMonthOfCovDate = getMonthFormat();
2729                             String previousMonthOfCovDate = coverageEndDate;
2730                             coverage.setCoverageEndDate(previousMonthOfCovDate);
2731                         } else {
2732                             coverageEndFlag = false;
2733                         }
2734                     } else if (coverageEndDate.matches(monthsAgo)) {
2735                         String[] coverageEndMonths = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2736                         if (coverageEndMonths.length > 0 && !coverageEndMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2737                             //String previousMonthsOfCovDate = getMonthsFormat(coverageEndMonths);
2738                             String previousMonthsOfCovDate = coverageEndDate;
2739                             coverage.setCoverageEndDate(previousMonthsOfCovDate);
2740                         } else {
2741                             coverageEndFlag = false;
2742                         }
2743                     } else if (coverageEndDate.matches(weekAgo)) {
2744                         String[] coverageEndWeek = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2745                         if (coverageEndWeek.length > 0 && coverageEndWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2746                             //String previousWeekOfCovEndDate = getWeekFormat();
2747                             String previousWeekOfCovEndDate = coverageEndDate;
2748                             coverage.setCoverageEndDate(previousWeekOfCovEndDate);
2749                         } else {
2750                             coverageEndFlag = false;
2751                         }
2752                     } else if (coverageEndDate.matches(weeksAgo)) {
2753                         String[] coverageEndWeeks = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2754                         if (coverageEndWeeks.length > 0 && !coverageEndWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2755                             //String previousWeeksOfCovEndDate = getWeeksFormat(coverageEndWeeks);
2756                             String previousWeeksOfCovEndDate = coverageEndDate;
2757                             coverage.setCoverageEndDate(previousWeeksOfCovEndDate);
2758                         } else {
2759                             coverageEndFlag = false;
2760                         }
2761                     } else if (coverageEndDate.matches(dayAgo)) {
2762                         String[] coverageEndDay = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2763                         if (coverageEndDay.length > 0 && coverageEndDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2764                             //String previousDayOfCovDate = getDayFormat();
2765                             String previousDayOfCovDate = coverageEndDate;
2766                             coverage.setCoverageEndDate(previousDayOfCovDate);
2767                         } else {
2768                             coverageEndFlag = false;
2769                         }
2770                     } else if (coverageEndDate.matches(daysAgo)) {
2771                         String[] coverageEndDays = coverageEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2772                         if (coverageEndDays.length > 0 && !coverageEndDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2773                             //String previousDaysOfCovEndDate = getDaysFormat(coverageEndDays);
2774                             String previousDaysOfCovEndDate = coverageEndDate;
2775                             coverage.setCoverageEndDate(previousDaysOfCovEndDate);
2776                         } else {
2777                             coverageEndFlag = false;
2778                         }
2779                     } else {
2780                         coverageEndFlag = false;
2781                     }
2782                 }
2783             }
2784         } catch (Exception ex) {
2785             LOG.error("Exception while validating the coverage end date format in EHoldings " + ex.getMessage());
2786             throw new RuntimeException();
2787         }
2788         return coverageEndFlag;
2789     }
2790 
2791     private boolean validatePerpetualAccessStartDates(PerpetualAccess perpetualAccess) {
2792         boolean perpetualAccessStartFlag = true;
2793         String perpetualAccessStartDate = "";
2794         try {
2795             if (perpetualAccess != null) {
2796                 perpetualAccessStartDate = perpetualAccess.getPerpetualAccessStartDate();
2797                 if (StringUtils.isNotEmpty(perpetualAccessStartDate)) {
2798                     if (perpetualAccessStartDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2799                         //String dateFormat = getDateFormat(perpetualAccessStartDate);
2800                         String dateFormat = perpetualAccessStartDate;
2801                         perpetualAccess.setPerpetualAccessStartDate(dateFormat);
2802                     } else if (perpetualAccessStartDate.matches(calendarYearAgo)) {
2803                         String[] perpetualAccessStartYear = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2804                         if (perpetualAccessStartYear.length > 0 && perpetualAccessStartYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2805                             /*String previousYearOfPerpetualAccDate = getYearFormat();
2806                             previousYearOfPerpetualAccDate = getFirstDay(previousYearOfPerpetualAccDate);*/
2807                             String previousYearOfPerpetualAccDate = perpetualAccessStartDate;
2808                             perpetualAccess.setPerpetualAccessStartDate(previousYearOfPerpetualAccDate);
2809                         } else {
2810                             perpetualAccessStartFlag = false;
2811                         }
2812                     } else if (perpetualAccessStartDate.matches(calendarYearsAgo)) {
2813                         String[] perpetualAccessStartYears = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2814                         if (perpetualAccessStartYears.length > 0 && !perpetualAccessStartYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2815                             /*String previousYearsOfPerpetualAccDate = getYearsFormat(perpetualAccessStartYears);
2816                             previousYearsOfPerpetualAccDate = getFirstDay(previousYearsOfPerpetualAccDate);*/
2817                             String previousYearsOfPerpetualAccDate = perpetualAccessStartDate;
2818                             perpetualAccess.setPerpetualAccessStartDate(previousYearsOfPerpetualAccDate);
2819                         } else {
2820                             perpetualAccessStartFlag = false;
2821                         }
2822                     } else if (perpetualAccessStartDate.matches(monthAgo)) {
2823                         String[] perpetualAccessStartMonth = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2824                         if (perpetualAccessStartMonth.length > 0 && perpetualAccessStartMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2825                             //String previousMonthOfPerpetualAccDate = getMonthFormat();
2826                             String previousMonthOfPerpetualAccDate = perpetualAccessStartDate;
2827                             perpetualAccess.setPerpetualAccessStartDate(previousMonthOfPerpetualAccDate);
2828                         } else {
2829                             perpetualAccessStartFlag = false;
2830                         }
2831                     } else if (perpetualAccessStartDate.matches(monthsAgo)) {
2832                         String[] perpetualAccessStartMonths = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2833                         if (perpetualAccessStartMonths.length > 0 && !perpetualAccessStartMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2834                             //String previousMonthsOfPerpetualAccDate = getMonthsFormat(perpetualAccessStartMonths);
2835                             String previousMonthsOfPerpetualAccDate = perpetualAccessStartDate;
2836                             perpetualAccess.setPerpetualAccessStartDate(previousMonthsOfPerpetualAccDate);
2837                         } else {
2838                             perpetualAccessStartFlag = false;
2839                         }
2840                     } else if (perpetualAccessStartDate.matches(weekAgo)) {
2841                         String[] perpetualAccessStartWeek = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2842                         if (perpetualAccessStartWeek.length > 0 && perpetualAccessStartWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2843                             //String previousWeekOfCovEndDate = getWeekFormat();
2844                             String previousWeekOfCovEndDate = perpetualAccessStartDate;
2845                             perpetualAccess.setPerpetualAccessStartDate(previousWeekOfCovEndDate);
2846                         } else {
2847                             perpetualAccessStartFlag = false;
2848                         }
2849                     } else if (perpetualAccessStartDate.matches(weeksAgo)) {
2850                         String[] perpetualAccessStartWeeks = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2851                         if (perpetualAccessStartWeeks.length > 0 && !perpetualAccessStartWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2852                             //String previousWeeksOfCovEndDate = getWeeksFormat(perpetualAccessStartWeeks);
2853                             String previousWeeksOfCovEndDate = perpetualAccessStartDate;
2854                             perpetualAccess.setPerpetualAccessStartDate(previousWeeksOfCovEndDate);
2855                         } else {
2856                             perpetualAccessStartFlag = false;
2857                         }
2858                     } else if (perpetualAccessStartDate.matches(dayAgo)) {
2859                         String[] perpetualAccessStartDay = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2860                         if (perpetualAccessStartDay.length > 0 && perpetualAccessStartDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2861                             //String previousDayOfPerpetualAccDate = getDayFormat();
2862                             String previousDayOfPerpetualAccDate = perpetualAccessStartDate;
2863                             perpetualAccess.setPerpetualAccessStartDate(previousDayOfPerpetualAccDate);
2864                         } else {
2865                             perpetualAccessStartFlag = false;
2866                         }
2867                     } else if (perpetualAccessStartDate.matches(daysAgo)) {
2868                         String[] perpetualAccessStartDays = perpetualAccessStartDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2869                         if (perpetualAccessStartDays.length > 0 && !perpetualAccessStartDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2870                             //String previousDaysOfPerpetualAccDate = getDaysFormat(perpetualAccessStartDays);
2871                             String previousDaysOfPerpetualAccDate = perpetualAccessStartDate;
2872                             perpetualAccess.setPerpetualAccessStartDate(previousDaysOfPerpetualAccDate);
2873                         } else {
2874                             perpetualAccessStartFlag = false;
2875                         }
2876                     } else {
2877                         perpetualAccessStartFlag = false;
2878                     }
2879                 }
2880             }
2881         } catch (Exception ex) {
2882             LOG.error("Exception while validating the Perpetual access start date format in EHoldings " + ex.getMessage());
2883             throw new RuntimeException();
2884         }
2885         return perpetualAccessStartFlag;
2886     }
2887 
2888     private boolean validatePerpetualAccessEndDates(PerpetualAccess perpetualAccess) {
2889         boolean perpetualAccessEndFlag = true;
2890         String perpetualAccessEndDate = "";
2891         try {
2892             if (perpetualAccess != null) {
2893                 perpetualAccessEndDate = perpetualAccess.getPerpetualAccessEndDate();
2894                 if (StringUtils.isNotEmpty(perpetualAccessEndDate)) {
2895                     if (perpetualAccessEndDate.matches(convertDateFormatToRegex(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE))) {
2896                         //String dateFormat = getDateFormat(perpetualAccessEndDate);
2897                         String dateFormat = perpetualAccessEndDate;
2898                         perpetualAccess.setPerpetualAccessEndDate(dateFormat);
2899                     } else if (perpetualAccessEndDate.matches(calendarYearAgo)) {
2900                         String[] perpetualAccessEndYear = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2901                         if (perpetualAccessEndYear.length > 0 && perpetualAccessEndYear[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2902                             /*String previousYearOfPerpetualAccDate = getYearFormat();
2903                             previousYearOfPerpetualAccDate = getLastDay(previousYearOfPerpetualAccDate);*/
2904                             String previousYearOfPerpetualAccDate = perpetualAccessEndDate;
2905                             perpetualAccess.setPerpetualAccessEndDate(previousYearOfPerpetualAccDate);
2906                         } else {
2907                             perpetualAccessEndFlag = false;
2908                         }
2909                     } else if (perpetualAccessEndDate.matches(calendarYearsAgo)) {
2910                         String[] perpetualAccessEndYears = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2911                         if (perpetualAccessEndYears.length > 0 && !perpetualAccessEndYears[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2912                             /*String previousYearsOfPerpetualAccDate = getYearsFormat(perpetualAccessEndYears);
2913                             previousYearsOfPerpetualAccDate = getLastDay(previousYearsOfPerpetualAccDate);*/
2914                             String previousYearsOfPerpetualAccDate = perpetualAccessEndDate;
2915                             perpetualAccess.setPerpetualAccessEndDate(previousYearsOfPerpetualAccDate);
2916                         } else {
2917                             perpetualAccessEndFlag = false;
2918                         }
2919                     } else if (perpetualAccessEndDate.matches(monthAgo)) {
2920                         String[] perpetualAccessEndMonth = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2921                         if (perpetualAccessEndMonth.length > 0 && perpetualAccessEndMonth[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2922                             //String previousMonthOfPerpetualAccDate = getMonthFormat();
2923                             String previousMonthOfPerpetualAccDate = perpetualAccessEndDate;
2924                             perpetualAccess.setPerpetualAccessEndDate(previousMonthOfPerpetualAccDate);
2925                         } else {
2926                             perpetualAccessEndFlag = false;
2927                         }
2928                     } else if (perpetualAccessEndDate.matches(monthsAgo)) {
2929                         String[] perpetualAccessEndMonths = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2930                         if (perpetualAccessEndMonths.length > 0 && !perpetualAccessEndMonths[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2931                             //String previousMonthsOfPerpetualAccDate = getMonthsFormat(perpetualAccessEndMonths);
2932                             String previousMonthsOfPerpetualAccDate = perpetualAccessEndDate;
2933                             perpetualAccess.setPerpetualAccessEndDate(previousMonthsOfPerpetualAccDate);
2934                         } else {
2935                             perpetualAccessEndFlag = false;
2936                         }
2937                     } else if (perpetualAccessEndDate.matches(weekAgo)) {
2938                         String[] perpetualAccessEndWeek = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2939                         if (perpetualAccessEndWeek.length > 0 && !perpetualAccessEndWeek[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2940                             //String previousWeekOfPerpetualAccDate = getWeekFormat();
2941                             String previousWeekOfPerpetualAccDate = perpetualAccessEndDate;
2942                             perpetualAccess.setPerpetualAccessEndDate(previousWeekOfPerpetualAccDate);
2943                         } else {
2944                             perpetualAccessEndFlag = false;
2945                         }
2946                     } else if (perpetualAccessEndDate.matches(weeksAgo)) {
2947                         String[] perpetualAccessEndWeeks = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2948                         if (perpetualAccessEndWeeks.length > 0 && !perpetualAccessEndWeeks[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2949                             //String previousWeeksOfPerpetualAccDate = getWeeksFormat(perpetualAccessEndWeeks);
2950                             String previousWeeksOfPerpetualAccDate = perpetualAccessEndDate;
2951                             perpetualAccess.setPerpetualAccessEndDate(previousWeeksOfPerpetualAccDate);
2952                         } else {
2953                             perpetualAccessEndFlag = false;
2954                         }
2955                     } else if (perpetualAccessEndDate.matches(dayAgo)) {
2956                         String[] perpetualAccessEndDay = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2957                         if (perpetualAccessEndDay.length > 0 && perpetualAccessEndDay[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2958                             //String previousDayOfPerpetualAccDate = getDayFormat();
2959                             String previousDayOfPerpetualAccDate = perpetualAccessEndDate;
2960                             perpetualAccess.setPerpetualAccessEndDate(previousDayOfPerpetualAccDate);
2961                         } else {
2962                             perpetualAccessEndFlag = false;
2963                         }
2964                     } else if (perpetualAccessEndDate.matches(daysAgo)) {
2965                         String[] perpetualAccessEndDays = perpetualAccessEndDate.split(OLEConstants.OLEEResourceRecord.SPACE);
2966                         if (perpetualAccessEndDays.length > 0 && !perpetualAccessEndDays[0].equals(OLEConstants.OLEEResourceRecord.ONE)) {
2967                             //String previousDaysOfPerpetualAccDate = getDaysFormat(perpetualAccessEndDays);
2968                             String previousDaysOfPerpetualAccDate = perpetualAccessEndDate;
2969                             perpetualAccess.setPerpetualAccessEndDate(previousDaysOfPerpetualAccDate);
2970                         } else {
2971                             perpetualAccessEndFlag = false;
2972                         }
2973                     } else {
2974                         perpetualAccessEndFlag = false;
2975                     }
2976                 }
2977             }
2978         } catch (Exception ex) {
2979             LOG.error("Exception while validating the Perpetual access end date format in EHoldings " + ex.getMessage());
2980             throw new RuntimeException();
2981         }
2982         return perpetualAccessEndFlag;
2983     }
2984 
2985     private String getDateFormat(String perpetualAccessEndDate) {
2986         Date date = new Date(perpetualAccessEndDate);
2987         String dateFormat = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(date);
2988         return dateFormat;
2989     }
2990 
2991     private String getYearFormat() {
2992         Calendar calendar = Calendar.getInstance();
2993         calendar.add(Calendar.YEAR, -1);
2994         Date previousYear = calendar.getTime();
2995         String year = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousYear);
2996         return year;
2997     }
2998 
2999     private String getYearsFormat(String[] years) {
3000         Calendar calendar = Calendar.getInstance();
3001         calendar.add(Calendar.YEAR, -(Integer.parseInt(years[0])));
3002         Date previousYears = calendar.getTime();
3003         String numberOfYears = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousYears);
3004         return numberOfYears;
3005     }
3006 
3007     private String getMonthFormat() {
3008         Calendar calendar = Calendar.getInstance();
3009         calendar.add(Calendar.MONTH, -1);
3010         Date previousMonth = calendar.getTime();
3011         String month = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousMonth);
3012         return month;
3013     }
3014 
3015     private String getMonthsFormat(String[] months) {
3016         Calendar calendar = Calendar.getInstance();
3017         calendar.add(Calendar.MONTH, -(Integer.parseInt(months[0])));
3018         Date previousMonths = calendar.getTime();
3019         String numberOfMonths = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousMonths);
3020         return numberOfMonths;
3021     }
3022 
3023     private String getWeekFormat() {
3024         Calendar calendar = Calendar.getInstance();
3025         int days = 7;
3026         calendar.add(Calendar.DATE, -(days));
3027         Date previousWeek = calendar.getTime();
3028         String week = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousWeek);
3029         return week;
3030     }
3031 
3032     private String getWeeksFormat(String[] weeks) {
3033         Calendar calendar = Calendar.getInstance();
3034         int days = Integer.parseInt(weeks[0]) * 7;
3035         calendar.add(Calendar.DATE, -(days));
3036         Date previousWeeks = calendar.getTime();
3037         String numberOfWeeks = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousWeeks);
3038         return numberOfWeeks;
3039     }
3040 
3041     private String getDayFormat() {
3042         Calendar calendar = Calendar.getInstance();
3043         calendar.add(Calendar.DATE, -1);
3044         Date previousDay = calendar.getTime();
3045         String day = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousDay);
3046         return day;
3047     }
3048 
3049     private String getDaysFormat(String[] days) {
3050         Calendar calendar = Calendar.getInstance();
3051         calendar.add(Calendar.DATE, -(Integer.parseInt(days[0])));
3052         Date previousDays = calendar.getTime();
3053         String numberOfDays = new SimpleDateFormat(OLEConstants.OLEEResourceRecord.DATE_FORMAT).format(previousDays);
3054         return numberOfDays;
3055     }
3056 
3057     private String getFirstDay(String firstDay) {
3058         String[] date = firstDay.split(OLEConstants.SLASH);
3059         String yearAlone = "";
3060         if (date.length > 1) {
3061             yearAlone = date[2];
3062         }
3063         yearAlone = firstDayOfYear + yearAlone;
3064         return yearAlone;
3065     }
3066 
3067     private String getLastDay(String lastDay) {
3068         String[] date = lastDay.split(OLEConstants.SLASH);
3069         String yearAlone = "";
3070         if (date.length > 1) {
3071             yearAlone = date[2];
3072         }
3073         yearAlone = lastDayOfYear + yearAlone;
3074         return yearAlone;
3075     }
3076 
3077     private void getPOAndInvoiceItemsWithoutDuplicate(OLEEResourceRecordDocument oleERSDoc) {
3078         List<OLEEResourcePO> oleeResourcePOItems = oleERSDoc.getOleERSPOItems();
3079         List<OLEEResourceInvoices> oleERSInvoices = oleERSDoc.getOleERSInvoices();
3080         Map avoidingDuplicateMap = new HashMap<>();
3081         for (OLEEResourcePO oleeResourcePO : oleeResourcePOItems) {
3082             avoidingDuplicateMap.put(oleeResourcePO.getOlePOItemId(),oleeResourcePO);
3083         }
3084         oleERSDoc.getOleERSPOItems().clear();
3085         oleERSDoc.getOleERSPOItems().addAll((Collection<? extends OLEEResourcePO>) avoidingDuplicateMap.values());
3086         oleERSDoc.getLinkedERSPOItems().clear();
3087         oleERSDoc.getLinkedERSPOItems().addAll((Collection<? extends OLEEResourcePO>) avoidingDuplicateMap.values());
3088         avoidingDuplicateMap.clear();
3089         for (OLEEResourceInvoices oleeResourceInvoice : oleERSInvoices) {
3090             avoidingDuplicateMap.put(oleeResourceInvoice.getInvoiceId(),oleeResourceInvoice);
3091         }
3092         oleERSDoc.getOleERSInvoices().clear();
3093         oleERSDoc.getOleERSInvoices().addAll((Collection<? extends OLEEResourceInvoices>) avoidingDuplicateMap.values());
3094     }
3095 
3096     public void getAcquisitionInfoFromPOAndInvoice(String holdingsId,WorkEInstanceOlemlForm workEInstanceOlemlForm) {
3097         Map map = new HashMap();
3098         map.put(OLEConstants.INSTANCE_ID, holdingsId);
3099         List<OleCopy> oleCopyList = (List) getBusinessObjectService().findMatching(OleCopy.class, map);
3100         StringBuffer linkedPos = new StringBuffer();
3101         StringBuffer vendor = new StringBuffer();
3102         StringBuffer orderType = new StringBuffer();
3103         StringBuffer orderFormat = new StringBuffer();
3104         StringBuffer fundCode = new StringBuffer();
3105         KualiDecimal currentFYCost=new KualiDecimal(0);
3106         for (OleCopy oleCopy : oleCopyList) {
3107             if (oleCopy.getPoItemId() != null) {
3108                 map.clear();
3109                 map.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, oleCopy.getPoItemId().toString());
3110                 OlePurchaseOrderItem olePurchaseOrderItem = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderItem.class, map);
3111                 if (olePurchaseOrderItem != null) {
3112                     // vendor, current FY cost & order type
3113                     map.clear();
3114                     map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
3115                     OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, map);
3116                     if (olePurchaseOrderDocument != null ){
3117                         // po
3118                         linkedPos.append(olePurchaseOrderDocument.getPurapDocumentIdentifier());
3119                         linkedPos.append(OLEConstants.COMMA);
3120                         linkedPos.append(' ');
3121                         Integer poId = olePurchaseOrderDocument.getPurapDocumentIdentifier();
3122                         vendor.append(olePurchaseOrderDocument.getVendorName());
3123                         vendor.append(OLEConstants.COMMA);
3124                         vendor.append(' ');
3125 
3126                         map.clear();
3127                         map.put(OLEConstants.PURCHASE_ORDER_TYPE_ID, olePurchaseOrderDocument.getPurchaseOrderTypeId());
3128                         Collection<PurchaseOrderType> purchaseOrderTypeDocumentList = getBusinessObjectService().findMatching(PurchaseOrderType.class, map);
3129                         if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
3130                             PurchaseOrderType purchaseOrderTypeDoc = purchaseOrderTypeDocumentList.iterator().next();
3131                             orderType.append(purchaseOrderTypeDoc.getPurchaseOrderType());
3132                             orderType.append(OLEConstants.SEMI_COLON);
3133                             orderType.append(' ');
3134                         }
3135                     }
3136                     // payment status & Fund code
3137                     map.clear();
3138                     map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, olePurchaseOrderItem.getItemIdentifier());
3139                     List<OleInvoiceItem> oleInvoiceItems = (List<OleInvoiceItem>) getBusinessObjectService().findMatching(OleInvoiceItem.class, map);
3140                     if (oleInvoiceItems != null && oleInvoiceItems.size() > 0) {
3141                         for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
3142                             map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, oleInvoiceItem.getItemIdentifier());
3143                             OlePaymentRequestItem olePaymentRequestItem = getBusinessObjectService().findByPrimaryKey(OlePaymentRequestItem.class, map);
3144                             if (olePaymentRequestItem != null) {
3145                                 workEInstanceOlemlForm.getExtendedEHoldingFields().setPaymentStatus(OLEConstants.PAID);
3146                                 break;
3147                             }
3148                         }
3149                         // fund code
3150                         Set<String> oleFundCodeList = new HashSet<>();
3151                         for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
3152                             List<PurApAccountingLine> purApAccountingLines = oleInvoiceItem.getSourceAccountingLines();
3153                             List<String> oleFundCodes = new ArrayList<>();
3154                             if (purApAccountingLines != null && purApAccountingLines.size() > 0) {
3155                                 oleFundCodes = getFundCodeList(purApAccountingLines);
3156                                 oleFundCodeList.addAll(oleFundCodes);
3157                             }
3158                         }
3159                         if(CollectionUtils.isNotEmpty(oleFundCodeList)){
3160                             for(String fundCodeId : oleFundCodeList){
3161                                 OleFundCode oleFundCode = new OleFundCode();
3162                                 Map fundCodeMap = new HashMap();
3163                                 fundCodeMap.put("fundCodeId",fundCodeId);
3164                                 oleFundCode = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleFundCode.class,fundCodeMap);
3165                                 if (oleFundCode != null){
3166                                     fundCode.append(oleFundCode.getFundCode());
3167                                     fundCode.append(OLEConstants.COMMA);
3168                                     fundCode.append(' ');
3169                                 }
3170                             }
3171                         }
3172                         if (fundCode.length() > 0) {
3173                             fundCode.deleteCharAt(fundCode.length() - 2);
3174                             workEInstanceOlemlForm.getExtendedEHoldingFields().setFundCode(fundCode.toString());
3175                         }
3176                     }
3177                     // order format
3178                     if (olePurchaseOrderItem.getFormatTypeId() != null) {
3179                         map.clear();
3180                         map.put(OLEConstants.FORMAT_TYPE_ID, olePurchaseOrderItem.getFormatTypeId());
3181                         OleFormatType oleFormatType = getBusinessObjectService().findByPrimaryKey(OleFormatType.class, map);
3182                         if (oleFormatType != null) {
3183                             orderFormat.append(oleFormatType.getFormatTypeName());
3184                             orderFormat.append(OLEConstants.COMMA);
3185                             orderFormat.append(' ');
3186                         }
3187                     }
3188                 }
3189             }
3190         }
3191         if (linkedPos.length() > 0) {
3192             if (vendor.length() > 0) {
3193                 String[] holdingVendors = vendor.toString().split(",");
3194                 Set set = new HashSet();
3195                 for (String holdingVendor : holdingVendors) {
3196                     set.add(holdingVendor.trim());
3197                 }
3198                 holdingVendors =  (String[]) set.toArray(new String[0]);
3199                 StringBuffer vendors = new StringBuffer();
3200                 for(String eholdingVendor : holdingVendors) {
3201                     vendors.append(eholdingVendor);
3202                 }
3203                 workEInstanceOlemlForm.getExtendedEHoldingFields().setVendorName(vendors.toString());
3204             }
3205             if (orderType.length() > 0) {
3206                 String[] holdingOrderTypes = orderType.toString().split(":");
3207                 Set set = new HashSet();
3208                 for (String holdingOrderType : holdingOrderTypes) {
3209                     set.add(holdingOrderType.trim());
3210                 }
3211                 holdingOrderTypes = (String[]) set.toArray(new String[0]);
3212                 StringBuffer orderTypes = new StringBuffer();
3213                 for(String eholdingOrderType : holdingOrderTypes) {
3214                     orderTypes.append(eholdingOrderType);
3215                 }
3216                 workEInstanceOlemlForm.getExtendedEHoldingFields().setOrderType(orderTypes.toString());
3217             }
3218             if (orderFormat.length() > 0) {
3219                 String[] orderFormats = orderFormat.toString().split(",");
3220                 Set set = new HashSet();
3221                 for (String orderFormatObject : orderFormats) {
3222                     set.add(orderFormatObject.trim());
3223                 }
3224                 orderFormats =  (String[]) set.toArray(new String[0]);
3225                 StringBuffer eholdingOrderFormats = new StringBuffer();
3226                 for(String eholdingOrderFormat : orderFormats) {
3227                     eholdingOrderFormats.append(eholdingOrderFormat);
3228                 }
3229                workEInstanceOlemlForm.getExtendedEHoldingFields().setOrderFormat(eholdingOrderFormats.toString());
3230             }
3231             String pos[] = linkedPos.toString().split(",");
3232             Set set = new HashSet();
3233             for (String po : pos) {
3234                 set.add(po.trim());
3235             }
3236             pos = (String[]) set.toArray(new String[0]);
3237             StringBuffer poLink = new StringBuffer();
3238             StringBuffer poNos = new StringBuffer();
3239             for (String po : pos) {
3240                 String link = null;
3241                 if (StringUtils.isNotBlank(po)) {
3242                     Map poMap = new HashMap();
3243                     poMap.put(org.kuali.ole.sys.OLEConstants.PUR_DOC_IDENTIFIER, po.trim());
3244                     List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = (List) getBusinessObjectService().findMatching(OlePurchaseOrderDocument.class, poMap);
3245                     if (olePurchaseOrderDocumentList != null && olePurchaseOrderDocumentList.size() > 0) {
3246                         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) {
3247                             boolean validPO = olePurchaseOrderDocumentList != null ? olePurchaseOrderDocument.getPurchaseOrderCurrentIndicatorForSearching() : false;
3248                             if (validPO) {
3249                                 link = ConfigContext.getCurrentContextConfig().getProperty("kew.url") + org.kuali.ole.sys.OLEConstants.PO_LINE_ITEM_URL + olePurchaseOrderDocument.getDocumentNumber();
3250                                 poLink.append("<a href=" + link + " target='_blank'>" + po.trim() + "</a>, ");
3251                                 poNos.append(po.trim());
3252                                 poNos.append(",");
3253                             }
3254                         }
3255                     }
3256                     currentFYCost = currentFYCost.add(getInvoicedAmount(po.trim()));
3257                 }
3258 
3259             }
3260             if (poLink.length() > 0) {
3261                 poLink.deleteCharAt(poLink.length() - 2);
3262                 workEInstanceOlemlForm.getExtendedEHoldingFields().setPurchaseOrderId(poLink.toString());
3263                 workEInstanceOlemlForm.getExtendedEHoldingFields().setPurchaseOrderNo(poNos.toString());
3264             }
3265             workEInstanceOlemlForm.getExtendedEHoldingFields().setCurrentFYCost(currentFYCost.toString());
3266             if (org.apache.commons.lang.StringUtils.isBlank(workEInstanceOlemlForm.getExtendedEHoldingFields().getPaymentStatus())) {
3267                 workEInstanceOlemlForm.getExtendedEHoldingFields().setPaymentStatus(OLEConstants.NOT_PAID);
3268             }
3269         }
3270     }
3271 
3272     public KualiDecimal getInvoicedAmount(String poId) {
3273         BigDecimal itemUnitPrice = BigDecimal.ZERO;
3274         Integer currentYear = getUniversityDateService().getCurrentFiscalYear();
3275         Map preqMap = new HashMap();
3276         preqMap.put(OLEConstants.PUR_ORDER_IDENTIFIER,poId);
3277         preqMap.put(OLEConstants.POSTING_YEAR,currentYear);
3278         List<OlePaymentRequestDocument> olePaymentRequestDocumentList = (List) getBusinessObjectService().findMatching(OlePaymentRequestDocument.class, preqMap);
3279         if(olePaymentRequestDocumentList.size() > 0) {
3280             for(OlePaymentRequestDocument olePaymentRequestDocument : olePaymentRequestDocumentList) {
3281                 preqMap.clear();
3282                 preqMap.put(OLEConstants.PURAP_DOC_IDENTIFIER,olePaymentRequestDocument.getPurapDocumentIdentifier());
3283                 preqMap.put(OLEConstants.ITEM_TYPE_CODE,OLEConstants.ITEM_TYP_CD_VALUE);
3284                 List<OlePaymentRequestItem> olePaymentRequestItemList = (List) getBusinessObjectService().findMatching(OlePaymentRequestItem.class,preqMap);
3285                 if(olePaymentRequestItemList.size() > 0) {
3286                     for(OlePaymentRequestItem olePaymentRequestItem : olePaymentRequestItemList) {
3287                         itemUnitPrice = itemUnitPrice.add(olePaymentRequestItem.getItemUnitPrice());
3288                     }
3289                 }
3290             }
3291         }
3292         preqMap.clear();
3293         preqMap.put(OLEConstants.PUR_ORDER_IDENTIFIER,poId);
3294         preqMap.put(OLEConstants.POSTING_YEAR,currentYear);
3295         List<OleVendorCreditMemoDocument> vendorCreditMemoDocumentList = (List) getBusinessObjectService().findMatching(OleVendorCreditMemoDocument.class,preqMap);
3296         if(vendorCreditMemoDocumentList.size() > 0) {
3297             for(OleVendorCreditMemoDocument vendorCreditMemoDocument : vendorCreditMemoDocumentList) {
3298                 preqMap.clear();
3299                 preqMap.put(OLEConstants.PURAP_DOC_IDENTIFIER,vendorCreditMemoDocument.getPurapDocumentIdentifier());
3300                 preqMap.put(OLEConstants.ITEM_TYPE_CODE,OLEConstants.ITEM_TYP_CD_VALUE);
3301                 List<OleCreditMemoItem> creditMemoItemList = (List) getBusinessObjectService().findMatching(OleCreditMemoItem.class,preqMap);
3302                 if(creditMemoItemList.size() > 0) {
3303                     for(OleCreditMemoItem creditMemoItem : creditMemoItemList) {
3304                         itemUnitPrice = itemUnitPrice.subtract(creditMemoItem.getItemUnitPrice());
3305                     }
3306                 }
3307 
3308             }
3309         }
3310         return new KualiDecimal(itemUnitPrice);
3311     }
3312 
3313     private List<String> getFundCodeList(List<PurApAccountingLine> purApAccountingLines) {
3314         int totalInvoiceAccountLine = purApAccountingLines.size();
3315         List<List<String>> oleFundCodeIdList = new ArrayList<>();
3316         List<String> fundCodes = new ArrayList<>();
3317         for(PurApAccountingLine purApAccountingLine : purApAccountingLines){
3318             List<OleFundCodeAccountingLine> oleFundCodeAccountingLines = new ArrayList<>();
3319             OLESelectDaoOjb oleSelectDaoOjb = (OLESelectDaoOjb) SpringContext.getBean("oleSelectDaoOjb");
3320             if(oleSelectDaoOjb != null){
3321                 oleFundCodeAccountingLines = oleSelectDaoOjb.getFundCodeList(purApAccountingLine);
3322             }
3323             if(CollectionUtils.isNotEmpty(oleFundCodeAccountingLines)){
3324                 List<String> fundCodeIdList = new ArrayList<>();
3325                 for (Iterator<OleFundCodeAccountingLine> iterator = oleFundCodeAccountingLines.iterator(); iterator.hasNext(); ) {
3326                     OleFundCodeAccountingLine oleFundCodeAccountingLine = iterator.next();
3327                     fundCodeIdList.add(oleFundCodeAccountingLine.getFundCodeId());
3328                 }
3329                 if(CollectionUtils.isNotEmpty(fundCodeIdList)){
3330                     oleFundCodeIdList.add(fundCodeIdList);
3331                 }
3332             }
3333         }
3334         if(CollectionUtils.isNotEmpty(oleFundCodeIdList) && oleFundCodeIdList.size() == totalInvoiceAccountLine){
3335             List<String> oleFundCodeList = oleFundCodeIdList.get(0);
3336             for(int index = 1; index < oleFundCodeIdList.size();index++){
3337                 List<String> fundCodeList = oleFundCodeIdList.get(index);
3338                 oleFundCodeList.retainAll(fundCodeList);
3339             }
3340             fundCodes.addAll(oleFundCodeList);
3341         }
3342         return fundCodes;
3343     }
3344 
3345     private void updateEResInOleCopy(Holdings holdings, OLEEResourceRecordDocument oleERSDoc) {
3346         Map<String, String> criteriaMap = new HashMap<>();
3347         criteriaMap.put(OLEConstants.INSTANCE_ID, holdings.getId());
3348         List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
3349                 criteriaMap);
3350         if (copies.size() > 0) {
3351             oleERSDoc.getCopyList().addAll(copies);
3352         } else {
3353             List<OleCopy> newCopies = new ArrayList<OleCopy>();
3354             OleCopy oleCopy = new OleCopy();
3355             oleCopy.setBibId(holdings.getBib().getId());
3356             oleCopy.setOleERSIdentifier(oleERSDoc.getOleERSIdentifier() != null ? oleERSDoc.getOleERSIdentifier() : "");
3357             oleCopy.setInstanceId(holdings.getId());
3358             newCopies.add(oleCopy);
3359             oleERSDoc.getCopyList().addAll(newCopies);
3360         }
3361     }
3362 
3363     @Override
3364     public void removeDuplicateEresDocumentsFromList(List<OLEEResourceRecordDocument> eresourceDocumentList) {
3365         Map eresourceMap = new HashMap();
3366         List eResourceList = new ArrayList();
3367         for (OLEEResourceRecordDocument oleEResourceRecordDocument : eresourceDocumentList) {
3368             eresourceMap.put(oleEResourceRecordDocument.getDocumentNumber(), oleEResourceRecordDocument);
3369         }
3370         eResourceList.addAll((Set) eresourceMap.keySet());
3371         eresourceDocumentList.clear();
3372         for (int eResourceCount = 0; eResourceCount < eResourceList.size(); eResourceCount++) {
3373             eresourceDocumentList.add((OLEEResourceRecordDocument) eresourceMap.get(eResourceList.get(eResourceCount)));
3374         }
3375     }
3376 
3377     @Override
3378     public List<OLEEResourceRecordDocument> filterEResRecBystatusDate(Date beginDate, Date endDate,List<OLEEResourceRecordDocument> eresourceList) {
3379         List<OLEEResourceRecordDocument> eresourceDocumentList = new ArrayList<OLEEResourceRecordDocument>();
3380         try {
3381             String begin = null;
3382             if (beginDate != null) {
3383                 begin = dateFormat.format(beginDate);
3384             }
3385             String end = null;
3386             if (endDate != null) {
3387                 end = dateFormat.format(endDate);
3388             }
3389             boolean isValid = false;
3390             eresourceDocumentList.clear();
3391             for (OLEEResourceRecordDocument oleEResourceRecordDocumentList : eresourceList) {
3392                 String status = oleEResourceRecordDocumentList.getStatusDate();
3393                 Date statusDate = simpleDateFormat.parse(status);
3394                 OleLicenseRequestServiceImpl oleLicenseRequestService = GlobalResourceLoader.getService(OLEConstants.OleLicenseRequest.LICENSE_REQUEST_SERVICE);
3395                 isValid = oleLicenseRequestService.validateDate(statusDate, begin, end);
3396                 if (isValid) {
3397                     eresourceDocumentList.add(oleEResourceRecordDocumentList);
3398                 }
3399             }
3400         } catch (Exception e) {
3401             LOG.error("Exception while calling the licenseRequest service" + e.getMessage());
3402             throw new RuntimeException(e);
3403         }
3404         return eresourceDocumentList;
3405     }
3406 
3407     @Override
3408     public List<RequisitionItem> generateItemList(OLEEResourceOrderRecord oleEResourceOrderRecord, OleRequisitionDocument requisitionDocument) throws Exception {
3409         List<RequisitionItem> items = new ArrayList<RequisitionItem>();
3410         int itemLineNumber = 1;
3411         items.add(createRequisitionItem(oleEResourceOrderRecord, itemLineNumber, requisitionDocument));
3412         return items;
3413     }
3414 
3415     @Override
3416     public List<RequisitionItem> generateMultipleItemsForOneRequisition(List<OLEEResourceOrderRecord> oleEResourceOrderRecordList, OleRequisitionDocument requisitionDocument) throws Exception {
3417         List<RequisitionItem> items = new ArrayList<RequisitionItem>();
3418         int itemLineNumber = 0;
3419         for (OLEEResourceOrderRecord oleEResourceOrderRecord : oleEResourceOrderRecordList) {
3420             itemLineNumber++;
3421             items.add(createRequisitionItem(oleEResourceOrderRecord, itemLineNumber, requisitionDocument));
3422         }
3423         return items;
3424     }
3425 
3426     private RequisitionItem createRequisitionItem(OLEEResourceOrderRecord oleEResourceOrderRecord, int itemLineNumber, OleRequisitionDocument requisitionDocument) throws Exception {
3427         OleRequisitionItem item = new OleRequisitionItem();
3428         item.setOleEResourceOrderRecord(oleEResourceOrderRecord);
3429         item.setItemLineNumber(itemLineNumber);
3430         item.setItemUnitOfMeasureCode(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.UOM));
3431         item.setItemQuantity(new KualiDecimal(oleEResourceOrderRecord.getOleEResourceTxnRecord().getQuantity()));
3432         item.setItemNoOfParts(new KualiInteger(oleEResourceOrderRecord.getOleEResourceTxnRecord().getItemNoOfParts()));
3433         item.setItemUnitPrice(new BigDecimal(oleEResourceOrderRecord.getOleEResourceTxnRecord().getListPrice()));
3434         item.setItemTypeCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getItemType());
3435         item.setItemListPrice(new KualiDecimal(oleEResourceOrderRecord.getOleEResourceTxnRecord().getListPrice()));
3436         item.setItemLocation(oleEResourceOrderRecord.getOleEResourceTxnRecord().getDefaultLocation());
3437         if (ObjectUtils.isNotNull(oleEResourceOrderRecord.getOleBibRecord()) && ObjectUtils.isNotNull(oleEResourceOrderRecord.getOleBibRecord().getBibUUID())) {
3438             item.setItemTitleId(oleEResourceOrderRecord.getOleBibRecord().getBibUUID());
3439         } else if (StringUtils.isNotBlank(oleEResourceOrderRecord.getOleERSIdentifier())) {
3440             item.setOleERSIdentifier(oleEResourceOrderRecord.getOleERSIdentifier());
3441         }
3442         if (oleEResourceOrderRecord.getBibTree()!=null){
3443             item.setBibTree(oleEResourceOrderRecord.getBibTree());
3444         }
3445         item.setPurposeId(oleEResourceOrderRecord.getOleEResourceTxnRecord().getPurposeId());
3446         item.setLinkToOrderOption(oleEResourceOrderRecord.getLinkToOrderOption());
3447         org.kuali.ole.module.purap.businessobject.ItemType itemType = getBusinessObjectService().findBySinglePrimaryKey(org.kuali.ole.module.purap.businessobject.ItemType.class, "ITEM");
3448         item.setItemType(itemType);
3449 
3450         List<PurApAccountingLine> sourceAccountingLines = new ArrayList<>();
3451         if (oleEResourceOrderRecord.getOleEResourceTxnRecord().getCretePOAccountingLines() != null) {
3452             for (OLECretePOAccountingLine cretePOAccountingLine : oleEResourceOrderRecord.getOleEResourceTxnRecord().getCretePOAccountingLines()) {
3453                 RequisitionAccount requisitionAccount = new RequisitionAccount();
3454                 requisitionAccount.setChartOfAccountsCode(cretePOAccountingLine.getChartOfAccountsCode());
3455                 requisitionAccount.setAccountNumber(cretePOAccountingLine.getAccountNumber());
3456                 if (StringUtils.isNotBlank(cretePOAccountingLine.getSubAccountNumber())){
3457                     requisitionAccount.setSubAccountNumber(cretePOAccountingLine.getSubAccountNumber());
3458                 }
3459                 requisitionAccount.setFinancialObjectCode(cretePOAccountingLine.getFinancialObjectCode());
3460                 if (StringUtils.isNotBlank(cretePOAccountingLine.getFinancialSubObjectCode())){
3461                     requisitionAccount.setFinancialSubObjectCode(cretePOAccountingLine.getFinancialSubObjectCode());
3462                 }
3463                 if (StringUtils.isNotBlank(cretePOAccountingLine.getProjectCode())){
3464                     requisitionAccount.setProjectCode(cretePOAccountingLine.getProjectCode());
3465                 }
3466                 if (StringUtils.isNotBlank(cretePOAccountingLine.getOrganizationReferenceId())){
3467                     requisitionAccount.setOrganizationReferenceId(cretePOAccountingLine.getOrganizationReferenceId());
3468                 }
3469                 requisitionAccount.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
3470                 if (StringUtils.isNotBlank(oleEResourceOrderRecord.getOleEResourceTxnRecord().getListPrice())) {
3471                     requisitionAccount.setAmount(new KualiDecimal(oleEResourceOrderRecord.getOleEResourceTxnRecord().getListPrice()));
3472                 }
3473                 requisitionAccount.setAccountLinePercent(cretePOAccountingLine.getAccountLinePercent());
3474                 sourceAccountingLines.add(requisitionAccount);
3475             }
3476         }
3477         item.setSourceAccountingLines(sourceAccountingLines);
3478 
3479         if (oleEResourceOrderRecord.getOleBibRecord() != null) {
3480             setItemDescription(oleEResourceOrderRecord, item);
3481         } else if (StringUtils.isNotBlank(oleEResourceOrderRecord.getOleERSIdentifier())) {
3482             OLEEResourceRecordDocument oleeResourceRecordDocument = getBusinessObjectService().findBySinglePrimaryKey(OLEEResourceRecordDocument.class, oleEResourceOrderRecord.getOleERSIdentifier());
3483             if (oleeResourceRecordDocument != null) {
3484                 item.setItemDescription(oleeResourceRecordDocument.getTitle());
3485             }
3486         }
3487         setForeignCurrencyDetails(item,requisitionDocument);
3488         return item;
3489     }
3490 
3491     private void setForeignCurrencyDetails(OleRequisitionItem item,OleRequisitionDocument requisitionDocument){
3492         boolean currencyTypeIndicator = true;
3493         if (requisitionDocument.getVendorDetail().getCurrencyType()!=null){
3494             if(requisitionDocument.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
3495                 currencyTypeIndicator=true;
3496             }
3497             else{
3498                 currencyTypeIndicator=false;
3499             }
3500         }
3501         if(!currencyTypeIndicator){
3502             item.setItemForeignListPrice(item.getItemListPrice());
3503             item.setItemForeignDiscountType(item.getItemDiscountType());
3504             item.setItemForeignDiscount(item.getItemDiscount());
3505             item.setItemListPrice(new KualiDecimal(0.00));
3506             getOlePurapService().calculateForeignCurrency(item);
3507             Long currencyTypeId = requisitionDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId();
3508             Map documentNumberMap = new HashMap();
3509             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
3510             List<OleExchangeRate> exchangeRateList = (List) getBusinessObjectService().findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
3511             Iterator iterator = exchangeRateList.iterator();
3512             if (iterator.hasNext()) {
3513                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
3514                 item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
3515             }
3516             if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
3517                 item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
3518                 item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue());
3519                 item.setItemListPrice(item.getItemUnitCostUSD());
3520             }
3521         }
3522     }
3523 
3524     @Override
3525     public List<OLEEResourceOrderRecord> fetchOleOrderRecordList(List<OLECreatePO> createPOs, String linkToOrderOption, String location) throws Exception {
3526         List<OLEEResourceOrderRecord> oleEResourceOrderRecordList = new ArrayList<>();
3527         for (OLECreatePO createPO : createPOs) {
3528             OLEEResourceOrderRecord oleEResourceOrderRecord = new OLEEResourceOrderRecord();
3529             oleEResourceOrderRecord.addMessageToMap(OLEConstants.IS_VALID_RECORD, true);
3530             oleEResourceOrderRecord.addMessageToMap(OLEConstants.IS_APO_RULE, true);
3531             oleEResourceOrderRecord.setLinkToOrderOption(linkToOrderOption);
3532 
3533             if (createPO.getBibId() != null) {
3534                 BibId bibTree = new BibId();
3535                 bibTree.setId(createPO.getBibId());
3536                 HoldingsId holdingsId = new HoldingsId();
3537                 holdingsId.setId(createPO.getInstanceId());
3538                 bibTree.getHoldingsIds().add(holdingsId);
3539                 oleEResourceOrderRecord.setBibTree(bibTree);
3540                 oleEResourceOrderRecord.setBibId(bibTree.getId());
3541 
3542                 OleBibRecord oleBibRecord = new OleBibRecord();
3543                 oleBibRecord.setBibUUID(createPO.getBibId());
3544                 oleBibRecord.setBib(getDocstoreClientLocator().getDocstoreClient().retrieveBib(createPO.getBibId()));
3545                 oleEResourceOrderRecord.setOleBibRecord(oleBibRecord);
3546             }else if (StringUtils.isNotBlank(createPO.getOleERSIdentifier())){
3547                 oleEResourceOrderRecord.setOleERSIdentifier(createPO.getOleERSIdentifier());
3548             }
3549 
3550             OLEEResourceTxnRecord oleEResourceTxnRecord = new OLEEResourceTxnRecord();
3551             oleEResourceTxnRecord.setCostSource(getParameter(OLEConstants.OLEEResourceRecord.COST_SOURCE,OLEConstants.ERESOURCE_CMPNT));
3552             oleEResourceTxnRecord.setMethodOfPOTransmission(getParameter(OLEConstants.OLEEResourceRecord.METHOD_OF_PO_TRANSMISSION, OLEConstants.ERESOURCE_CMPNT));
3553             oleEResourceTxnRecord.setDefaultLocation(location);
3554             oleEResourceTxnRecord.setVendorNumber(createPO.getVendorId());
3555             oleEResourceTxnRecord.setDeliveryBuildingRoomNumber(getParameter(OLEConstants.OLEEResourceRecord.BUILDING_ROOM_NUMBER, OLEConstants.ERESOURCE_CMPNT));
3556             oleEResourceTxnRecord.setDeliveryCampusCode(getParameter(OLEConstants.OLEEResourceRecord.DELIVERY_CAMPUS_CODE, OLEConstants.ERESOURCE_CMPNT));
3557             oleEResourceTxnRecord.setBuildingCode(getParameter(OLEConstants.OLEEResourceRecord.BUILDING_CODE, OLEConstants.ERESOURCE_CMPNT));
3558             if (StringUtils.isNotBlank(createPO.getPrice())){
3559                 oleEResourceTxnRecord.setListPrice(createPO.getPrice());
3560             }else {
3561                 oleEResourceTxnRecord.setListPrice("0");
3562             }
3563             oleEResourceTxnRecord.setChartCode(getParameter(OLEConstants.OLEEResourceRecord.CHART_CODE, OLEConstants.ERESOURCE_CMPNT));
3564             oleEResourceTxnRecord.setOrgCode(getParameter(OLEConstants.OLEEResourceRecord.ORG_CODE, OLEConstants.ERESOURCE_CMPNT));
3565             oleEResourceTxnRecord.setFundingSource(getParameter(OLEConstants.OLEEResourceRecord.FUNDING_SOURCE, OLEConstants.ERESOURCE_CMPNT));
3566             oleEResourceTxnRecord.setCretePOAccountingLines(createPO.getAccountingLines());
3567             oleEResourceTxnRecord.setItemType(OLEConstants.ITEM_TYP);
3568             oleEResourceTxnRecord.setRequisitionSource(OleSelectConstant.REQUISITON_SRC_TYPE_AUTOINGEST);
3569             if (StringUtils.isNotBlank(createPO.getInstanceFlag()) && createPO.getInstanceFlag().equalsIgnoreCase("true")) {
3570                 oleEResourceTxnRecord.setQuantity("1");
3571                 oleEResourceTxnRecord.setItemNoOfParts("1");
3572             }else {
3573                 oleEResourceTxnRecord.setQuantity(getParameter(OLEConstants.OLEEResourceRecord.QUANTITY, OLEConstants.ERESOURCE_CMPNT));
3574                 oleEResourceTxnRecord.setItemNoOfParts(getParameter(OLEConstants.OLEEResourceRecord.NO_OF_PARTS, OLEConstants.ERESOURCE_CMPNT));
3575             }
3576             oleEResourceTxnRecord.setOrderType(createPO.getOrderTypeId());
3577             oleEResourceTxnRecord.setPurposeId(createPO.getPurposeId());
3578             oleEResourceOrderRecord.setOleEResourceTxnRecord(oleEResourceTxnRecord);
3579             oleEResourceOrderRecordList.add(oleEResourceOrderRecord);
3580         }
3581         return oleEResourceOrderRecordList;
3582     }
3583 
3584     /*public void setUserForOrderRecords(List<OleOrderRecord> oleOrderRecords) {
3585         String user = null;
3586         if (oleOrderRecords.size() > 0) {
3587             user = GlobalVariables.getUserSession().getPrincipalName();
3588             if (user == null) {
3589                 user = getConfigurationService().getPropertyValueAsString(
3590                         OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR);
3591             }
3592             GlobalVariables.setUserSession(new UserSession(user));
3593         }
3594     }*/
3595 
3596     @Override
3597     public String validateAccountngLinesVendorAndPrice(OLECreatePO createPO) {
3598         String validationMsg = new String();
3599         BigDecimal totalPercentage = BigDecimal.ZERO;
3600         BigDecimal desiredPercent = new BigDecimal("100");
3601         if (createPO.getAccountingLines()!=null && createPO.getAccountingLines().size()>0){
3602             for (OLECretePOAccountingLine cretePOAccountingLine : createPO.getAccountingLines()){
3603                 validationMsg = validateAccountingLines(validationMsg, cretePOAccountingLine);
3604                 totalPercentage = totalPercentage.add(cretePOAccountingLine.getAccountLinePercent());
3605             }
3606             if (desiredPercent.compareTo(totalPercentage) != 0) {
3607                 validationMsg = validationMsg.concat("The total percent of the accounts must equal 100%");
3608             }
3609         }else {
3610             validationMsg = validationMsg.concat("Atleast one accounting line should be there");
3611         }
3612         if (StringUtils.isBlank(createPO.getVendorId())) {
3613             if (validationMsg.length() > 1) {
3614                 validationMsg = validationMsg.concat(", ");
3615             }
3616             validationMsg = validationMsg.concat("Vendor is required");
3617         }
3618         if (StringUtils.isNotBlank(createPO.getPrice())) {
3619             try {
3620                 new BigDecimal(createPO.getPrice());
3621             } catch (Exception e) {
3622                 if (validationMsg.length() > 1) {
3623                     validationMsg = validationMsg.concat(" and ");
3624                 }
3625                 validationMsg = validationMsg.concat("Invalid Estimated Price");
3626             }
3627 
3628         }
3629         if (validationMsg.length() > 1) {
3630             validationMsg = validationMsg.concat(" for '" + createPO.getTitle() + "'");
3631             validationMsg = validationMsg.concat(OLEConstants.BREAK);
3632         }
3633         return validationMsg;
3634     }
3635 
3636     @Override
3637     public String getParameter(String parameterName, String componentName) {
3638         LOG.debug("Inside getParameter()");
3639         String parameter = "";
3640         try {
3641             Map<String, String> criteriaMap = new HashMap<String, String>();
3642             criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.SELECT_NMSPC);
3643             criteriaMap.put(OLEConstants.COMPONENT_CODE, componentName);
3644             criteriaMap.put(OLEConstants.NAME_SELECTOR, parameterName);
3645             List<ParameterBo> parametersList = (List<ParameterBo>) getBusinessObjectService().findMatching(ParameterBo.class, criteriaMap);
3646             for (ParameterBo parameterBo : parametersList) {
3647                 parameter = parameterBo.getValue();
3648             }
3649         } catch (Exception e) {
3650             LOG.error("Exception while getting parameter value", e);
3651         }
3652         LOG.debug("End of getParameter()");
3653         return parameter;
3654     }
3655 
3656     @Override
3657     public void getBannerMessage(OLEEResourceRecordDocument oleEResourceRecordDocument) {
3658         Set<String> platformIds = new HashSet<>();
3659         String bannerMessage = new String();
3660         for (OLEEResourceInstance eResourceInstance : oleEResourceRecordDocument.getOleERSInstances()) {
3661             if (StringUtils.isNotBlank(eResourceInstance.getPlatformId())) {
3662                 platformIds.add(eResourceInstance.getPlatformId());
3663             }
3664         }
3665         if (platformIds.size() > 0) {
3666                 Map platformMap = new HashMap();
3667             platformMap.put(OLEConstants.OLE_PLATFORM_ID, platformIds);
3668             List<OLEPlatformRecordDocument> olePlatformRecordDocumentList = (List<OLEPlatformRecordDocument>) getBusinessObjectService().findMatching(OLEPlatformRecordDocument.class, platformMap);
3669             if (CollectionUtils.isNotEmpty(olePlatformRecordDocumentList)) {
3670                 for (OLEPlatformRecordDocument olePlatformRecordDocument : olePlatformRecordDocumentList) {
3671                 if (olePlatformRecordDocument != null) {
3672                     List<OLEPlatformEventLog> olePlatformEventLogList = olePlatformRecordDocument.getEventLogs();
3673                     for (OLEPlatformEventLog olePlatformEventLog : olePlatformEventLogList) {
3674                             if (StringUtils.isNotBlank(olePlatformEventLog.getLogTypeId()) && olePlatformEventLog.getLogTypeId().equals("2")) {
3675                                 if (StringUtils.isNotBlank(olePlatformEventLog.getEventStatus()) && !olePlatformEventLog.getEventStatus().equals("Resolved")) {
3676                                     bannerMessage = bannerMessage.concat("NOTICE: " + olePlatformRecordDocument.getName() + " is experiencing a problem " + makeUrlClickable(olePlatformRecordDocument.getDocumentNumber()) + " for more details.");
3677                                     bannerMessage = bannerMessage.concat(OLEConstants.BREAK);
3678                                 break;
3679                             }
3680                         }
3681                     }
3682                 }
3683             }
3684         }
3685         }
3686         oleEResourceRecordDocument.setBannerMessage(bannerMessage);
3687     }
3688 
3689     @Override
3690     public List<OLECreatePO> getInstances(OLEEResourceRecordDocument oleeResourceRecordDocument, String purposeId){
3691         List<OLEEResourceInstance> oleERSInstances = oleeResourceRecordDocument.getOleERSInstances();
3692         List<OLECreatePO> instancePOs = new ArrayList<>();
3693         for (OLEEResourceInstance oleeResourceInstance : oleERSInstances) {
3694             boolean poExists = false;
3695             boolean saveChanges = false;
3696             Map<String, String> criteriaMap = new HashMap<String, String>();
3697             criteriaMap.put(OLEConstants.INSTANCE_ID, oleeResourceInstance.getInstanceId());
3698             List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class, criteriaMap);
3699             for (OleCopy copy : copies) {
3700                 if (copy.getPoItemId() != null) {
3701                     Map<String, String> criteriaPOIdMap = new HashMap<String, String>();
3702                     criteriaPOIdMap.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, copy.getPoItemId().toString());
3703                     List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, criteriaPOIdMap);
3704                     if (olePurchaseOrderItems.size() > 0) {
3705                         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
3706                             Map map = new HashMap();
3707                             map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
3708                             OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, map);
3709                             if (olePurchaseOrderDocument != null) {
3710                                 poExists = true;
3711                                 OLECreatePO instancePO = new OLECreatePO();
3712                                 instancePO.setPoId(olePurchaseOrderDocument.getPurapDocumentIdentifier().toString());
3713                                 instancePO.setInstanceFlag(oleeResourceInstance.getInstanceFlag());
3714                                 instancePO.setInstanceId(oleeResourceInstance.getInstanceId());
3715                                 instancePO.setBibId(oleeResourceInstance.getBibId());
3716                                 instancePO.setTitle(oleeResourceInstance.getInstanceTitle());
3717                                 instancePO.setGokbId("0002");
3718                                 instancePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3719                                 instancePO.setVendorId(olePurchaseOrderDocument.getVendorNumber());
3720                                 instancePO.setOrderTypeId(olePurchaseOrderDocument.getPurchaseOrderTypeId().toString());
3721                                 instancePO.setPrice(olePurchaseOrderItem.getItemListPrice().toString());
3722                                 instancePO.setPurposeId(olePurchaseOrderItem.getPurposeId());
3723                                 List<OLECretePOAccountingLine> accountingLines = new ArrayList<>();
3724                                 if (olePurchaseOrderItem.getSourceAccountingLines() != null && olePurchaseOrderItem.getSourceAccountingLines().size() > 0) {
3725                                     for (PurApAccountingLine purApAccountingLine : olePurchaseOrderItem.getSourceAccountingLines()){
3726                                         OLECretePOAccountingLine oleCretePOAccountingLine = new OLECretePOAccountingLine();
3727                                         oleCretePOAccountingLine.setChartOfAccountsCode(purApAccountingLine.getChartOfAccountsCode());
3728                                         oleCretePOAccountingLine.setAccountNumber(purApAccountingLine.getAccountNumber());
3729                                         oleCretePOAccountingLine.setSubAccountNumber(purApAccountingLine.getSubAccountNumber());
3730                                         oleCretePOAccountingLine.setFinancialObjectCode(purApAccountingLine.getFinancialObjectCode());
3731                                         oleCretePOAccountingLine.setFinancialSubObjectCode(purApAccountingLine.getFinancialSubObjectCode());
3732                                         oleCretePOAccountingLine.setProjectCode(purApAccountingLine.getProjectCode());
3733                                         oleCretePOAccountingLine.setOrganizationReferenceId(purApAccountingLine.getOrganizationReferenceId());
3734                                         oleCretePOAccountingLine.setAccountLinePercent(purApAccountingLine.getAccountLinePercent());
3735                                         accountingLines.add(oleCretePOAccountingLine);
3736                                     }
3737                                     instancePO.setAccountingLines(accountingLines);
3738                                 }
3739                                 instancePOs.add(instancePO);
3740                             }
3741                         }
3742                     }
3743                 }
3744             }
3745             Map createPoMap = new HashMap();
3746             createPoMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
3747             List<OLECreatePO> oleCreatePOs = (List<OLECreatePO>) getBusinessObjectService().findMatching(OLECreatePO.class,createPoMap);
3748             if (oleCreatePOs!=null && oleCreatePOs.size()>0){
3749                 for (OLECreatePO oleCreatePO : oleCreatePOs){
3750                     if (StringUtils.isNotBlank(oleCreatePO.getInstanceId())){
3751                         saveChanges =true;
3752                         OLECreatePO instancePO = new OLECreatePO();
3753                         instancePO.setSelectFlag(true);
3754                         instancePO.setOleERSIdentifier(oleeResourceRecordDocument.getOleERSIdentifier());
3755                         instancePO.setInstanceFlag(oleCreatePO.getInstanceFlag());
3756                         instancePO.setInstanceId(oleCreatePO.getInstanceId());
3757                         instancePO.setBibId(oleeResourceInstance.getBibId());
3758                         instancePO.setTitle(oleeResourceInstance.getInstanceTitle());
3759                         instancePO.setGokbId("0002");
3760                         instancePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3761                         instancePO.setVendorId(oleCreatePO.getVendorId());
3762                         instancePO.setOrderTypeId(oleCreatePO.getOrderTypeId().toString());
3763                         instancePO.setPrice(oleCreatePO.getPrice());
3764                         instancePO.setPurposeId(oleCreatePO.getPurposeId());
3765                         instancePO.setAccountingLines(oleCreatePO.getAccountingLines());
3766                         instancePOs.add(instancePO);
3767                     }
3768                 }
3769             }
3770             if (!poExists && !saveChanges) {
3771                 OLECreatePO instancePO = new OLECreatePO();
3772                 instancePO.setOleERSIdentifier(oleeResourceRecordDocument.getOleERSIdentifier());
3773                 instancePO.setInstanceFlag(oleeResourceInstance.getInstanceFlag());
3774                 instancePO.setInstanceId(oleeResourceInstance.getInstanceId());
3775                 instancePO.setBibId(oleeResourceInstance.getBibId());
3776                 instancePO.setTitle(oleeResourceInstance.getInstanceTitle());
3777                 instancePO.setGokbId("0002");
3778                 instancePO.setAccountingLines(getOLECretePOAccountingLines(oleeResourceRecordDocument.getAccountingLines()));
3779                 instancePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3780                 instancePO.setVendorId(oleeResourceRecordDocument.getVendorId());
3781                 instancePO.setOrderTypeId(oleeResourceRecordDocument.getOrderTypeId().toString());
3782                 instancePO.setPrice(oleeResourceRecordDocument.getEstimatedPrice());
3783                 instancePO.setPurposeId(purposeId);
3784                 instancePOs.add(instancePO);
3785             }
3786         }
3787         List<OLECreatePO> instancePOsWithoutDuplicate = removeDuplicateForPOInstanceAndEResource(instancePOs);
3788         return instancePOsWithoutDuplicate;
3789     }
3790 
3791 
3792     private List<OLECreatePO> removeDuplicateForPOInstanceAndEResource(List<OLECreatePO> objectList) {
3793         Map avoidingDuplicateMap = new HashMap<>();
3794         for (OLECreatePO oleCreatePO : objectList) {
3795             avoidingDuplicateMap.put(oleCreatePO.getPoId(),oleCreatePO);
3796         }
3797         objectList.clear();
3798         objectList.addAll((Collection<? extends OLECreatePO>) avoidingDuplicateMap.values());
3799         return objectList;
3800     }
3801 
3802     @Override
3803     public List<OLECreatePO> getEresources(OLEEResourceRecordDocument oleeResourceRecordDocument, String purposeId) {
3804         List<OLECreatePO> eResources = new ArrayList<>();
3805         boolean poExists = false;
3806         boolean saveChanges = false;
3807         Map<String, String> criteriaMap = new HashMap<String, String>();
3808         criteriaMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
3809         criteriaMap.put(OLEConstants.LOC, "E-Resource");
3810         List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class, criteriaMap);
3811         for (OleCopy copy : copies) {
3812             if (copy.getPoItemId() != null) {
3813                 Map<String, String> criteriaPOIdMap = new HashMap<String, String>();
3814                 criteriaPOIdMap.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, copy.getPoItemId().toString());
3815                 List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, criteriaPOIdMap);
3816                 if (olePurchaseOrderItems.size() > 0) {
3817                     for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
3818                         Map map = new HashMap();
3819                         map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
3820                         OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, map);
3821                         if (olePurchaseOrderDocument != null) {
3822                             poExists = true;
3823                             OLECreatePO eResourcePO = new OLECreatePO();
3824                             eResourcePO.setPoId(olePurchaseOrderDocument.getPurapDocumentIdentifier().toString());
3825                             eResourcePO.setTitle(oleeResourceRecordDocument.getTitle());
3826                             eResourcePO.setGokbId("0002");
3827                             eResourcePO.setOleERSIdentifier(oleeResourceRecordDocument.getOleERSIdentifier());
3828                             eResourcePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3829                             eResourcePO.setVendorId(olePurchaseOrderDocument.getVendorNumber());
3830                             eResourcePO.setOrderTypeId(olePurchaseOrderDocument.getPurchaseOrderTypeId().toString());
3831                             eResourcePO.setPrice(olePurchaseOrderItem.getItemListPrice().toString());
3832                             eResourcePO.setPurposeId(olePurchaseOrderItem.getPurposeId());
3833                             List<OLECretePOAccountingLine> accountingLines = new ArrayList<>();
3834                             if (olePurchaseOrderItem.getSourceAccountingLines() != null && olePurchaseOrderItem.getSourceAccountingLines().size() > 0) {
3835                                 for (PurApAccountingLine purApAccountingLine : olePurchaseOrderItem.getSourceAccountingLines()){
3836                                     OLECretePOAccountingLine oleCretePOAccountingLine = new OLECretePOAccountingLine();
3837                                     oleCretePOAccountingLine.setChartOfAccountsCode(purApAccountingLine.getChartOfAccountsCode());
3838                                     oleCretePOAccountingLine.setAccountNumber(purApAccountingLine.getAccountNumber());
3839                                     oleCretePOAccountingLine.setSubAccountNumber(purApAccountingLine.getSubAccountNumber());
3840                                     oleCretePOAccountingLine.setFinancialObjectCode(purApAccountingLine.getFinancialObjectCode());
3841                                     oleCretePOAccountingLine.setFinancialSubObjectCode(purApAccountingLine.getFinancialSubObjectCode());
3842                                     oleCretePOAccountingLine.setProjectCode(purApAccountingLine.getProjectCode());
3843                                     oleCretePOAccountingLine.setOrganizationReferenceId(purApAccountingLine.getOrganizationReferenceId());
3844                                     oleCretePOAccountingLine.setAccountLinePercent(purApAccountingLine.getAccountLinePercent());
3845                                     accountingLines.add(oleCretePOAccountingLine);
3846                                 }
3847                                 eResourcePO.setAccountingLines(accountingLines);
3848                             }
3849                             eResources.add(eResourcePO);
3850                         }
3851                     }
3852                 }
3853             }
3854         }
3855         Map createPoMap = new HashMap();
3856         createPoMap.put(OLEConstants.OLEEResourceRecord.ERESOURCE_IDENTIFIER, oleeResourceRecordDocument.getOleERSIdentifier());
3857         List<OLECreatePO> oleCreatePOs = (List<OLECreatePO>) getBusinessObjectService().findMatching(OLECreatePO.class,createPoMap);
3858         if (oleCreatePOs!=null && oleCreatePOs.size()>0){
3859             for (OLECreatePO oleCreatePO : oleCreatePOs){
3860                 if (StringUtils.isBlank(oleCreatePO.getInstanceId())){
3861                     saveChanges = true;
3862                     OLECreatePO eResourcePO = new OLECreatePO();
3863                     eResourcePO.setSelectFlag(true);
3864                     eResourcePO.setTitle(oleeResourceRecordDocument.getTitle());
3865                     eResourcePO.setGokbId(oleeResourceRecordDocument.getGokbId());
3866                     eResourcePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3867                     eResourcePO.setPrice(oleeResourceRecordDocument.getEstimatedPrice());
3868                     eResourcePO.setVendorId(oleCreatePO.getVendorId());
3869                     eResourcePO.setOrderTypeId(oleCreatePO.getOrderTypeId().toString());
3870                     eResourcePO.setOleERSIdentifier(oleeResourceRecordDocument.getOleERSIdentifier());
3871                     eResourcePO.setPurposeId(oleCreatePO.getPurposeId());
3872                     eResourcePO.setAccountingLines(oleCreatePO.getAccountingLines());
3873                     eResources.add(eResourcePO);
3874                 }
3875             }
3876         }
3877         if (!poExists && !saveChanges) {
3878             OLECreatePO eResourcePO = new OLECreatePO();
3879             eResourcePO.setTitle(oleeResourceRecordDocument.getTitle());
3880             eResourcePO.setGokbId(oleeResourceRecordDocument.getGokbId());
3881             eResourcePO.setAccountingLines(getOLECretePOAccountingLines(oleeResourceRecordDocument.getAccountingLines()));
3882             eResourcePO.setIsbnNIssn(oleeResourceRecordDocument.getIsbn());
3883             eResourcePO.setPrice(oleeResourceRecordDocument.getEstimatedPrice());
3884             eResourcePO.setVendorId(oleeResourceRecordDocument.getVendorId());
3885             eResourcePO.setOrderTypeId(oleeResourceRecordDocument.getOrderTypeId().toString());
3886             eResourcePO.setOleERSIdentifier(oleeResourceRecordDocument.getOleERSIdentifier());
3887             eResourcePO.setPurposeId(purposeId);
3888             eResources.add(eResourcePO);
3889         }
3890         List<OLECreatePO> eResourcePOsWithoutDuplicate =removeDuplicateForPOInstanceAndEResource(eResources);
3891         return eResourcePOsWithoutDuplicate;
3892     }
3893 
3894     @Override
3895     public String validateAccountingLines(String errorMessage, OLECretePOAccountingLine accountingLine) {
3896         //chart code validation
3897         Chart chart = getBusinessObjectService().findBySinglePrimaryKey(Chart.class, accountingLine.getChartOfAccountsCode());
3898         if (chart == null) {
3899             if (errorMessage.length() > 1) {
3900                 errorMessage = errorMessage.concat(", ");
3901             }
3902             errorMessage = errorMessage.concat("Invalid Chart Code");
3903         }
3904         //Account no validation
3905         Map accNoMap = new HashMap();
3906         accNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
3907         Account account = getBusinessObjectService().findByPrimaryKey(Account.class, accNoMap);
3908         if (account == null) {
3909             if (errorMessage.length() > 1) {
3910                 errorMessage = errorMessage.concat(", ");
3911             }
3912             errorMessage = errorMessage.concat("Invalid Account Number");
3913         } else {
3914             accNoMap = new HashMap();
3915             accNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
3916             accNoMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
3917             List<Account> accountList = (List<Account>) getBusinessObjectService().findMatching(Account.class, accNoMap);
3918             if (accountList.size() == 0) {
3919                 if (errorMessage.length() > 1) {
3920                     errorMessage = errorMessage.concat(", ");
3921                 }
3922                 errorMessage = errorMessage.concat("The combination of Chart Code and account number is not valid");
3923             }
3924         }
3925         //Object Code validation
3926         UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
3927         Integer fiscalYear = universityDateService.getCurrentUniversityDate().getUniversityFiscalYear();
3928         Map objectCodeMap = new HashMap();
3929         objectCodeMap.put(OLEConstants.OLEBatchProcess.OBJECT_CODE, accountingLine.getFinancialObjectCode());
3930         objectCodeMap.put(org.kuali.ole.sys.OLEConstants.FISCAL_YEAR, fiscalYear);
3931         List<ObjectCode> objectCodeList = (List<ObjectCode>) getBusinessObjectService().findMatching(ObjectCode.class, objectCodeMap);
3932         if (objectCodeList.size() == 0) {
3933             if (errorMessage.length() > 1) {
3934                 errorMessage = errorMessage.concat(", ");
3935             }
3936             errorMessage = errorMessage.concat("Invalid Object Code");
3937         }
3938         //Sub-Account no validation
3939         String subAccNo = accountingLine.getSubAccountNumber();
3940         if (org.apache.commons.lang3.StringUtils.isNotBlank(subAccNo)) {
3941             Map subAccNoMap = new HashMap();
3942             subAccNoMap.put(OLEConstants.SUB_ACCOUNT_NUMBER, subAccNo);
3943             SubAccount subAccount = getBusinessObjectService().findByPrimaryKey(SubAccount.class, subAccNoMap);
3944             if (subAccount == null) {
3945                 if (errorMessage.length() > 1) {
3946                     errorMessage = errorMessage.concat(", ");
3947                 }
3948                 errorMessage = errorMessage.concat("Invalid Sub Account Number");
3949             } else {
3950                 subAccNoMap = new HashMap();
3951                 subAccNoMap.put(OLEConstants.SUB_ACCOUNT_NUMBER, subAccNo);
3952                 subAccNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
3953                 subAccNoMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
3954                 List<SubAccount> subAccountList = (List<SubAccount>) getBusinessObjectService().findMatching(SubAccount.class, subAccNoMap);
3955                 if (subAccountList.size() == 0) {
3956                     if (errorMessage.length() > 1) {
3957                         errorMessage = errorMessage.concat(", ");
3958                     }
3959                     errorMessage = errorMessage.concat("The combination of Chart Code, Account number and Sub-Account number is not valid");
3960                 }
3961             }
3962         }
3963         //Sub Object Code validation
3964         String subObjectCode = accountingLine.getFinancialSubObjectCode();
3965         if (org.apache.commons.lang3.StringUtils.isNotBlank(subObjectCode)) {
3966             Map subObjectCodeMap = new HashMap();
3967             subObjectCodeMap.put(OLEConstants.FINANCIAL_SUB_OBJECT_CODE, subObjectCode);
3968             SubObjectCode subObject = getBusinessObjectService().findByPrimaryKey(SubObjectCode.class, subObjectCodeMap);
3969             if (subObject == null) {
3970                 if (errorMessage.length() > 1) {
3971                     errorMessage = errorMessage.concat(", ");
3972                 }
3973                 errorMessage = errorMessage.concat("Invalid Sub Object Code");
3974             } else {
3975                 subObjectCodeMap = new HashMap();
3976                 subObjectCodeMap.put(OLEConstants.FINANCIAL_SUB_OBJECT_CODE, subObjectCode);
3977                 subObjectCodeMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
3978                 subObjectCodeMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
3979                 subObjectCodeMap.put(OLEConstants.OLEBatchProcess.OBJECT_CODE, accountingLine.getFinancialObjectCode());
3980                 subObjectCodeMap.put(org.kuali.ole.sys.OLEConstants.FISCAL_YEAR, fiscalYear);
3981                 List<SubObjectCode> subObjectCodeList = (List<SubObjectCode>) getBusinessObjectService().findMatching(SubObjectCode.class, subObjectCodeMap);
3982                 if (subObjectCodeList.size() == 0) {
3983                     if (errorMessage.length() > 1) {
3984                         errorMessage = errorMessage.concat(", ");
3985                     }
3986                     errorMessage = errorMessage.concat("The combination of Chart Code, Account number, Object Code & Sub-Object Code is not valid");
3987                 }
3988             }
3989         }
3990         //Project Code validation
3991         String projectCode = accountingLine.getProjectCode();
3992         if (org.apache.commons.lang3.StringUtils.isNotBlank(projectCode)) {
3993             Map projectCodeMap = new HashMap();
3994             projectCodeMap.put(OLEConstants.CODE, projectCode);
3995             List<ProjectCode> projectCodeList = (List<ProjectCode>) getBusinessObjectService().findMatching(ProjectCode.class, projectCodeMap);
3996             if (projectCodeList.size() == 0) {
3997                 if (errorMessage.length() > 1) {
3998                     errorMessage = errorMessage.concat(", ");
3999                 }
4000                 errorMessage = errorMessage.concat("Invalid Project Code");
4001             }
4002         }
4003         return errorMessage;
4004     }
4005 
4006     @Override
4007     public boolean validateAccountingLines(OLEEResourceAccountingLine accountingLine, String sectionId) {
4008         boolean flag = false;
4009         //chart code validation
4010         Chart chart = getBusinessObjectService().findBySinglePrimaryKey(Chart.class, accountingLine.getChartOfAccountsCode());
4011         if (chart == null) {
4012             GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_CHART_CODE);
4013             flag = true;
4014         }
4015         //Account no validation
4016         Map accNoMap = new HashMap();
4017         accNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
4018         Account account = getBusinessObjectService().findByPrimaryKey(Account.class, accNoMap);
4019         if (account == null) {
4020             GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_ACCOUNT_NUM);
4021             flag = true;
4022         } else {
4023             accNoMap = new HashMap();
4024             accNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
4025             accNoMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
4026             List<Account> accountList = (List<Account>) getBusinessObjectService().findMatching(Account.class, accNoMap);
4027             if (accountList.size() == 0) {
4028                 GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_COMBINATION_ACCOUNT_NUM);
4029                 flag = true;
4030             }
4031         }
4032         //Object Code validation
4033         UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
4034         Integer fiscalYear = universityDateService.getCurrentUniversityDate().getUniversityFiscalYear();
4035         Map objectCodeMap = new HashMap();
4036         objectCodeMap.put(OLEConstants.OLEBatchProcess.OBJECT_CODE, accountingLine.getFinancialObjectCode());
4037         objectCodeMap.put(org.kuali.ole.sys.OLEConstants.FISCAL_YEAR, fiscalYear);
4038         List<ObjectCode> objectCodeList = (List<ObjectCode>) getBusinessObjectService().findMatching(ObjectCode.class, objectCodeMap);
4039         if (objectCodeList.size() == 0) {
4040             GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_OBJECT_CODE);
4041             flag = true;
4042         }
4043         //Sub-Account no validation
4044         String subAccNo = accountingLine.getSubAccountNumber();
4045         if (org.apache.commons.lang3.StringUtils.isNotBlank(subAccNo)) {
4046             Map subAccNoMap = new HashMap();
4047             subAccNoMap.put(OLEConstants.SUB_ACCOUNT_NUMBER, subAccNo);
4048             SubAccount subAccount = getBusinessObjectService().findByPrimaryKey(SubAccount.class, subAccNoMap);
4049             if (subAccount == null) {
4050                 GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_SUB_ACCOUNT_NUM);
4051                 flag = true;
4052             } else {
4053                 subAccNoMap = new HashMap();
4054                 subAccNoMap.put(OLEConstants.SUB_ACCOUNT_NUMBER, subAccNo);
4055                 subAccNoMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
4056                 subAccNoMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
4057                 List<SubAccount> subAccountList = (List<SubAccount>) getBusinessObjectService().findMatching(SubAccount.class, subAccNoMap);
4058                 if (subAccountList.size() == 0) {
4059                     GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_COMBINATION_SUB_ACCOUNT_NUM);
4060                     flag = true;
4061                 }
4062             }
4063         }
4064         //Sub Object Code validation
4065         String subObjectCode = accountingLine.getFinancialSubObjectCode();
4066         if (org.apache.commons.lang3.StringUtils.isNotBlank(subObjectCode)) {
4067             Map subObjectCodeMap = new HashMap();
4068             subObjectCodeMap.put(OLEConstants.FINANCIAL_SUB_OBJECT_CODE, subObjectCode);
4069             SubObjectCode subObject = getBusinessObjectService().findByPrimaryKey(SubObjectCode.class, subObjectCodeMap);
4070             if (subObject == null) {
4071                 GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_SUB_OBJECT_CODE);
4072                 flag = true;
4073             } else {
4074                 subObjectCodeMap = new HashMap();
4075                 subObjectCodeMap.put(OLEConstants.FINANCIAL_SUB_OBJECT_CODE, subObjectCode);
4076                 subObjectCodeMap.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
4077                 subObjectCodeMap.put(OLEConstants.OLEBatchProcess.CHART_OF_ACCOUNTS_CODE, accountingLine.getChartOfAccountsCode());
4078                 subObjectCodeMap.put(OLEConstants.OLEBatchProcess.OBJECT_CODE, accountingLine.getFinancialObjectCode());
4079                 subObjectCodeMap.put(org.kuali.ole.sys.OLEConstants.FISCAL_YEAR, fiscalYear);
4080                 List<SubObjectCode> subObjectCodeList = (List<SubObjectCode>) getBusinessObjectService().findMatching(SubObjectCode.class, subObjectCodeMap);
4081                 if (subObjectCodeList.size() == 0) {
4082                     GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_COMBINATION_SUB_OBJECT_CODE);
4083                     flag = true;
4084                 }
4085             }
4086         }
4087         //Project Code validation
4088         String projectCode = accountingLine.getProjectCode();
4089         if (org.apache.commons.lang3.StringUtils.isNotBlank(projectCode)) {
4090             Map projectCodeMap = new HashMap();
4091             projectCodeMap.put(OLEConstants.CODE, projectCode);
4092             List<ProjectCode> projectCodeList = (List<ProjectCode>) getBusinessObjectService().findMatching(ProjectCode.class, projectCodeMap);
4093             if (projectCodeList.size() == 0) {
4094                 GlobalVariables.getMessageMap().putErrorForSectionId(sectionId, OLEConstants.OLEEResourceRecord.ERROR_INVALID_PROJECT_CODE);
4095                 flag = true;
4096             }
4097         }
4098         return flag;
4099     }
4100 
4101     @Override
4102     public RequisitionDocument setDocumentValues(OleRequisitionDocument requisitionDocument, OLEEResourceOrderRecord oleEResourceOrderRecord) throws Exception {
4103         // ******************Document Overview Section******************
4104         requisitionDocument.setStatusCode(PurapConstants.RequisitionStatuses.APPDOC_IN_PROCESS);
4105         /**
4106          * Commented vendorPoNumber based on JIRA-2842
4107          */
4108         //requisitionDocument.setVendorPoNumber(oleOrderRecord.getOleEResourceTxnRecord().getVendorNumber());
4109         requisitionDocument.setVendorPoNumber(oleEResourceOrderRecord.getOleEResourceTxnRecord().getVendorItemIdentifier());
4110         // ******************Financial Document Detail Section******************
4111         // ******************Requisition Detail Section******************
4112         requisitionDocument.setChartOfAccountsCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getChartCode());
4113         requisitionDocument.setOrganizationCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getOrgCode());
4114         requisitionDocument.setDocumentFundingSourceCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getFundingSource());
4115         requisitionDocument.setUseTaxIndicator(true);//oleOrderRecord.getOleEResourceTxnRecord().getUseTaxIndicator()
4116         // ******************Delivery Section******************
4117         setDeliveryDetails(requisitionDocument, oleEResourceOrderRecord);
4118         requisitionDocument.setDeliveryCampusCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryCampusCode());
4119         // ******************Vendor Section******************
4120         setVendorDetails(requisitionDocument, oleEResourceOrderRecord);
4121         // ******************Items Section******************
4122         // ******************Capital Assets Section******************
4123         // ******************Payment INfo Section******************
4124         // ******************Additional Institutional Info Section******************
4125         requisitionDocument.getDocumentHeader().setDocumentDescription("Document Description");
4126         requisitionDocument.setPurchaseOrderTransmissionMethodCode(getOleReqPOCreateDocumentService().getTransmissionMethodCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getMethodOfPOTransmission()));//FAX
4127         requisitionDocument.setPurchaseOrderCostSourceCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getCostSource());//CON
4128         requisitionDocument.setRequestorPersonName(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_NAME));
4129         requisitionDocument.setRequestorPersonPhoneNumber(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_PHONE_NUMBER));
4130         requisitionDocument.setRequestorPersonEmailAddress(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_EMAIL_ADDRESS));
4131         requisitionDocument.setOrganizationAutomaticPurchaseOrderLimit(new KualiDecimal(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.VENDOR_CONTRACT_DEFAULT_APO_LIMIT)));
4132         requisitionDocument.setPurchaseOrderAutomaticIndicator(Boolean.parseBoolean(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.PURCHASE_ORDER_AUTOMATIC_INDICATIOR)));
4133         requisitionDocument.setReceivingDocumentRequiredIndicator(oleEResourceOrderRecord.getOleEResourceTxnRecord().isReceivingRequired());
4134         requisitionDocument.setPaymentRequestPositiveApprovalIndicator(oleEResourceOrderRecord.getOleEResourceTxnRecord().isPayReqPositiveApprovalReq());
4135         requisitionDocument.setRequisitionSourceCode(oleEResourceOrderRecord.getOleEResourceTxnRecord().getRequisitionSource());
4136         return requisitionDocument;
4137     }
4138 
4139     @Override
4140     public void setItemDescription(OLEEResourceOrderRecord oleEResourceOrderRecord, OleRequisitionItem item) throws Exception {
4141         String title = oleEResourceOrderRecord.getOleBibRecord().getBib().getTitle() != null ? oleEResourceOrderRecord.getOleBibRecord().getBib().getTitle()+ "," : "";
4142         String author = oleEResourceOrderRecord.getOleBibRecord().getBib().getAuthor() != null ? oleEResourceOrderRecord.getOleBibRecord().getBib().getAuthor()+ "," : "";
4143         String publisher = oleEResourceOrderRecord.getOleBibRecord().getBib().getPublisher() != null ? oleEResourceOrderRecord.getOleBibRecord().getBib().getPublisher()+ "," : "";
4144         String isbn = oleEResourceOrderRecord.getOleBibRecord().getBib().getIsbn() != null ? oleEResourceOrderRecord.getOleBibRecord().getBib().getIsbn() + ",": "";
4145         String description = title + author
4146                 + publisher + isbn;
4147         item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
4148         item.setItemTitle(oleEResourceOrderRecord.getOleBibRecord().getBib().getTitle());
4149         item.setItemAuthor(oleEResourceOrderRecord.getOleBibRecord().getBib().getAuthor());
4150         item.setBibUUID(oleEResourceOrderRecord.getOleBibRecord().getBibUUID());
4151 
4152     }
4153 
4154     private void setDeliveryDetails(OleRequisitionDocument requisitionDocument, OLEEResourceOrderRecord oleEResourceOrderRecord) {
4155         if (LOG.isDebugEnabled())
4156             LOG.debug("bibInfoBean.getDeliveryBuildingCode----------->" + oleEResourceOrderRecord.getOleEResourceTxnRecord().getBuildingCode());
4157 
4158         if (oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryCampusCode() != null && oleEResourceOrderRecord.getOleEResourceTxnRecord().getBuildingCode() != null && oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryBuildingRoomNumber() != null) {
4159             Map<String,String> deliveryMap = new HashMap<>();
4160             deliveryMap.put(OLEConstants.OLEBatchProcess.BUILDING_CODE, oleEResourceOrderRecord.getOleEResourceTxnRecord().getBuildingCode());
4161             deliveryMap.put(OLEConstants.OLEBatchProcess.CAMPUS_CODE, oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryCampusCode());
4162             deliveryMap.put(OLEConstants.BUILDING_ROOM_NUMBER, oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryBuildingRoomNumber());
4163             Room room = getBusinessObjectService().findByPrimaryKey(Room.class, deliveryMap);
4164             Building building = getVendorService().getBuildingDetails(oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryCampusCode(), oleEResourceOrderRecord.getOleEResourceTxnRecord().getBuildingCode());
4165             if (building != null && room != null) {
4166                 requisitionDocument.setDeliveryBuildingCode(building.getBuildingCode());
4167                 requisitionDocument.setDeliveryCampusCode(building.getCampusCode());
4168                 requisitionDocument.setDeliveryBuildingLine1Address(building.getBuildingStreetAddress());
4169                 requisitionDocument.setDeliveryBuildingName(building.getBuildingName());
4170                 requisitionDocument.setDeliveryCityName(building.getBuildingAddressCityName());
4171                 requisitionDocument.setDeliveryStateCode(building.getBuildingAddressStateCode());
4172                 requisitionDocument.setDeliveryPostalCode(building.getBuildingAddressZipCode());
4173                 requisitionDocument.setDeliveryCountryCode(building.getBuildingAddressCountryCode());
4174                 requisitionDocument.setDeliveryBuildingRoomNumber(room.getBuildingRoomNumber());
4175                 requisitionDocument.setDeliveryToName(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.DELIVERY_TO_NAME));
4176 
4177                 requisitionDocument.setBillingCountryCode(building.getBuildingCode());
4178                 requisitionDocument.setBillingLine1Address(building.getBuildingStreetAddress());
4179                 requisitionDocument.setBillingName(building.getBuildingName());
4180                 requisitionDocument.setBillingCityName(building.getBuildingAddressCityName());
4181                 requisitionDocument.setBillingStateCode(building.getBuildingAddressStateCode());
4182                 requisitionDocument.setBillingPostalCode(building.getBuildingAddressZipCode());
4183                 requisitionDocument.setBillingCountryCode(building.getBuildingAddressCountryCode());
4184                 requisitionDocument.setBillingPhoneNumber(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.BILL_PHN_NBR));
4185 
4186             }
4187         }
4188     }
4189 
4190     private void setVendorDetails(OleRequisitionDocument requisitionDocument, OLEEResourceOrderRecord oleEResourceOrderRecord) {
4191         if (oleEResourceOrderRecord.getOleEResourceTxnRecord().getVendorNumber() != null) {
4192             VendorDetail vendorDetail = getVendorService().getVendorDetail(oleEResourceOrderRecord.getOleEResourceTxnRecord().getVendorNumber());
4193 
4194             requisitionDocument.setVendorCustomerNumber(oleEResourceOrderRecord.getOleEResourceTxnRecord().getVendorInfoCustomer());
4195             requisitionDocument.setVendorNumber(oleEResourceOrderRecord.getOleEResourceTxnRecord().getVendorNumber());
4196             requisitionDocument.setVendorNumber(vendorDetail.getVendorNumber());
4197             requisitionDocument.setVendorName(vendorDetail.getVendorName());
4198             requisitionDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
4199             requisitionDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
4200             requisitionDocument.setVendorDetail(vendorDetail);
4201             String deliveryCampus = oleEResourceOrderRecord.getOleEResourceTxnRecord().getDeliveryCampusCode();
4202             Integer headerId = null;
4203             Integer detailId = null;
4204             int dashInd = vendorDetail.getVendorNumber().indexOf('-');
4205             // make sure there's at least one char before and after '-'
4206             if (dashInd > 0 && dashInd < vendorDetail.getVendorNumber().length() - 1) {
4207                 headerId = new Integer(vendorDetail.getVendorNumber().substring(0, dashInd));
4208                 detailId = new Integer(vendorDetail.getVendorNumber().substring(dashInd + 1));
4209             }
4210             VendorAddress vendorAddress = getVendorService().getVendorDefaultAddress(headerId, detailId, VendorConstants.AddressTypes.PURCHASE_ORDER, deliveryCampus);
4211             getOleReqPOCreateDocumentService().setVendorAddress(vendorAddress, requisitionDocument);
4212 
4213             List<VendorContract> vendorContracts = vendorDetail.getVendorContracts();
4214             for (Iterator<VendorContract> vendorContract = vendorContracts.iterator(); vendorContract.hasNext(); ) {
4215                 requisitionDocument.setVendorContractGeneratedIdentifier((vendorContract.next()).getVendorContractGeneratedIdentifier());
4216             }
4217         }
4218 
4219     }
4220 
4221     private List<OLECretePOAccountingLine> getOLECretePOAccountingLines(List<OLEEResourceAccountingLine> oleeResourceAccountingLines){
4222         List<OLECretePOAccountingLine> accountingLines = new ArrayList<>();
4223         for (OLEEResourceAccountingLine accountingLine : oleeResourceAccountingLines){
4224             OLECretePOAccountingLine oleCretePOAccountingLine = new OLECretePOAccountingLine();
4225             oleCretePOAccountingLine.setChartOfAccountsCode(accountingLine.getChartOfAccountsCode());
4226             oleCretePOAccountingLine.setAccountNumber(accountingLine.getAccountNumber());
4227             oleCretePOAccountingLine.setSubAccountNumber(accountingLine.getSubAccountNumber());
4228             oleCretePOAccountingLine.setFinancialObjectCode(accountingLine.getFinancialObjectCode());
4229             oleCretePOAccountingLine.setFinancialSubObjectCode(accountingLine.getFinancialSubObjectCode());
4230             oleCretePOAccountingLine.setProjectCode(accountingLine.getProjectCode());
4231             oleCretePOAccountingLine.setOrganizationReferenceId(accountingLine.getOrganizationReferenceId());
4232             oleCretePOAccountingLine.setAccountLinePercent(accountingLine.getAccountLinePercent());
4233             accountingLines.add(oleCretePOAccountingLine);
4234         }
4235         return accountingLines;
4236     }
4237 
4238     public String makeUrlClickable(String docId){
4239         String url = ConfigContext.getCurrentContextConfig().getProperty("ole.platform.url") + PLATFORM_URL_START + docId + PLATFORM_URL_END;
4240         return HREF_START + url + HREF_END;
4241     }
4242 
4243     private void setDefaultValuesToVendor(VendorDetail vendorDetail) {
4244         List<VendorAddress> vendorAddresses = vendorDetail.getVendorAddresses();
4245         VendorHeader vendorHeader = vendorDetail.getVendorHeader();
4246         Map vendorTypeMap = new HashMap();
4247         vendorTypeMap.put("vendorTypeDescription", getParameter(OLEConstants.VENDOR_TYPE));
4248         List<VendorType> vendorTypes = (List<VendorType>) getBusinessObjectService().findMatching(VendorType.class, vendorTypeMap);
4249         if (vendorTypes != null && vendorTypes.size() > 0) {
4250             VendorType vendorType = vendorTypes.get(0);
4251             vendorHeader.setVendorTypeCode(vendorType.getVendorTypeCode());
4252         } else {
4253             vendorHeader.setVendorTypeCode("PO");
4254         }
4255 
4256         vendorHeader.setVendorForeignIndicator(false);
4257 
4258         Map ownershipTypeMap = new HashMap();
4259         ownershipTypeMap.put("vendorOwnershipDescription", getParameter(OLEConstants.OWNERSHIP_TYPE));
4260         List<OwnershipType> ownershipTypes = (List<OwnershipType>) getBusinessObjectService().findMatching(OwnershipType.class, ownershipTypeMap);
4261         if (ownershipTypes != null && ownershipTypes.size() > 0) {
4262             OwnershipType ownershipType = ownershipTypes.get(0);
4263             vendorHeader.setVendorOwnershipCode(ownershipType.getVendorOwnershipCode());
4264         } else {
4265             vendorHeader.setVendorOwnershipCode("CP");
4266         }
4267 
4268 
4269         Map currencyMap = new HashMap();
4270         currencyMap.put("currencyType", getParameter(OLEConstants.CURRENCY_TYPE));
4271         List<OleCurrencyType> oleCurrencyTypes = (List<OleCurrencyType>) getBusinessObjectService().findMatching(OleCurrencyType.class, currencyMap);
4272         if (oleCurrencyTypes != null && oleCurrencyTypes.size() > 0) {
4273             OleCurrencyType oleCurrencyType = oleCurrencyTypes.get(0);
4274             vendorDetail.setCurrencyTypeId(oleCurrencyType.getCurrencyTypeId());
4275         } else {
4276             vendorDetail.setCurrencyTypeId(new Long(1));
4277         }
4278 
4279         Map paymentMap = new HashMap();
4280         paymentMap.put("paymentMethod", getParameter(OLEConstants.PAYMENT_METHOD));
4281         List<OlePaymentMethod> olePaymentMethods = (List<OlePaymentMethod>) getBusinessObjectService().findMatching(OlePaymentMethod.class, paymentMap);
4282         if (olePaymentMethods != null && olePaymentMethods.size() > 0) {
4283             OlePaymentMethod olePaymentMethod = olePaymentMethods.get(0);
4284             vendorDetail.setPaymentMethodId(olePaymentMethod.getPaymentMethodId());
4285         } else {
4286             vendorDetail.setPaymentMethodId(1);
4287         }
4288 
4289         VendorAddress vendorAddress = new VendorAddress();
4290 
4291         Map addressMap = new HashMap();
4292         addressMap.put("vendorAddressTypeDescription", getParameter(OLEConstants.ADDRESS_TYPE));
4293         List<AddressType> addressTypes = (List<AddressType>) getBusinessObjectService().findMatching(AddressType.class, addressMap);
4294         if (addressTypes != null && addressTypes.size() > 0) {
4295             AddressType addressType = addressTypes.get(0);
4296             vendorAddress.setVendorAddressTypeCode(addressType.getVendorAddressTypeCode());
4297         } else {
4298             vendorAddress.setVendorAddressTypeCode("PO");
4299         }
4300         vendorAddress.setVendorLine1Address(getParameter(OLEConstants.ADDRESS));
4301         vendorAddress.setVendorStateCode(getParameter(OLEConstants.STATE));
4302         vendorAddress.setVendorCityName(getParameter(OLEConstants.CITY));
4303         vendorAddress.setVendorZipCode(getParameter(OLEConstants.POSTAL_CODE));
4304         vendorAddress.setVendorCountryCode(getParameter(OLEConstants.COUNTRY));
4305         vendorAddress.setActive(true);
4306         vendorAddress.setVendorDefaultAddressIndicator(true);
4307         vendorAddresses.add(vendorAddress);
4308     }
4309 
4310     public void createVendor(String organizationName, Integer gokbOrganizationId, String variantName) {
4311         try {
4312             FinancialSystemMaintenanceDocument financialSystemMaintenanceDocument = (FinancialSystemMaintenanceDocument) KRADServiceLocatorWeb.getDocumentService().getNewDocument(org.kuali.ole.sys.OLEConstants.Vendor.DOCUMENT_TYPE);
4313             VendorDetail vendorDetail = (VendorDetail) financialSystemMaintenanceDocument.getNewMaintainableObject().getDataObject();
4314             if (StringUtils.isNotBlank(organizationName)) {
4315                 vendorDetail.setVendorName(organizationName);
4316             } else {
4317                 vendorDetail.setVendorName(gokbOrganizationId.toString());
4318             }
4319             if (vendorDetail.getVendorName().length() < 40) {
4320                 financialSystemMaintenanceDocument.getDocumentHeader().setDocumentDescription(vendorDetail.getVendorName());
4321             } else {
4322                 String documentDescription = vendorDetail.getVendorName().substring(0, 39);
4323                 financialSystemMaintenanceDocument.getDocumentHeader().setDocumentDescription(documentDescription);
4324             }
4325             vendorDetail.setNonBillable(true);
4326             vendorDetail.setGokbId(gokbOrganizationId);
4327             if (org.apache.commons.lang.StringUtils.isNotBlank(variantName)) {
4328                 VendorAlias vendorAlias = new VendorAlias();
4329                 vendorAlias.setVendorAliasName(variantName);
4330                 vendorAlias.setGokbVendorAliasInd(true);
4331                 vendorAlias.setVendorAliasType(new AliasType());
4332                 vendorAlias.setActive(true);
4333                 vendorDetail.getVendorAliases().add(vendorAlias);
4334             }
4335             vendorDetail.setActiveIndicator(true);
4336 
4337             setDefaultValuesToVendor(vendorDetail);
4338 
4339             VendorEventLog vendorEventLog = new VendorEventLog();
4340             vendorEventLog.setLogTypeId("3");
4341             vendorEventLog.setDate(new Timestamp(System.currentTimeMillis()));
4342             vendorEventLog.setUserId(GlobalVariables.getUserSession().getPrincipalId());
4343             vendorEventLog.setNote("Vendor is created through Gokb import");
4344             vendorDetail.getEventLogs().add(vendorEventLog);
4345             KRADServiceLocatorWeb.getDocumentService().routeDocument(financialSystemMaintenanceDocument, null, null);
4346 
4347         } catch (Exception e) {
4348             LOG.error("Exception while routing vendor document through E-Resource" + e);
4349         }
4350     }
4351 
4352     public void updateVendor(VendorDetail vendorDetail, String organizationName) {
4353         if (org.apache.commons.lang.StringUtils.isNotBlank(organizationName)) {
4354             vendorDetail.setVendorName(organizationName);
4355         }
4356         vendorDetail.setGokbLastUpdated(new Timestamp(System.currentTimeMillis()));
4357         VendorEventLog vendorEventLog = new VendorEventLog();
4358         vendorEventLog.setLogTypeId("3");
4359         vendorEventLog.setDate(new Timestamp(System.currentTimeMillis()));
4360         vendorEventLog.setUserId(GlobalVariables.getUserSession().getPrincipalId());
4361         vendorEventLog.setNote("Vendor is Updated through Gokb import");
4362         vendorDetail.getEventLogs().add(vendorEventLog);
4363         getBusinessObjectService().save(vendorDetail);
4364     }
4365 
4366     private void setPlatformProviderDetails(Integer platformProviderId, OLEPlatformRecordDocument olePlatformRecordDocument) {
4367         Map vendorMap = new HashMap();
4368         vendorMap.put(OLEConstants.GOKB_ID, platformProviderId);
4369         List<VendorDetail> vendorDetailList = (List<VendorDetail>) getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
4370         if (vendorDetailList != null && vendorDetailList.size() > 0) {
4371             olePlatformRecordDocument.setVendorHeaderGeneratedIdentifier(vendorDetailList.get(0).getVendorHeaderGeneratedIdentifier());
4372             olePlatformRecordDocument.setVendorDetailAssignedIdentifier(vendorDetailList.get(0).getVendorDetailAssignedIdentifier());
4373         }
4374     }
4375 
4376     private String getPlatformStatusId(String platformStatus) {
4377         Map statusMap = new HashMap();
4378         statusMap.put(OLEConstants.PLATFORM_STATUS_NAME, platformStatus);
4379         List<OLEPlatformStatus> platformStatusList = (List<OLEPlatformStatus>) getBusinessObjectService().findMatching(OLEPlatformStatus.class, statusMap);
4380         if (platformStatusList != null && platformStatusList.size() > 0) {
4381             return platformStatusList.get(0).getPlatformStatusId();
4382         }
4383         return null;
4384     }
4385 
4386     public OLEPlatformRecordDocument createPlatform(String platformName, Integer gokbPlatformId, String softwarePlatform, String platformStatus, Integer platformProviderId) {
4387         try {
4388             OLEPlatformRecordDocument olePlatformRecordDocument = (OLEPlatformRecordDocument) KRADServiceLocatorWeb.getDocumentService().getNewDocument(OLEConstants.OLE_PLATFORM_DOC);
4389             if (org.apache.commons.lang.StringUtils.isNotBlank(platformName)) {
4390                 olePlatformRecordDocument.setName(platformName);
4391             } else {
4392                 olePlatformRecordDocument.setName(gokbPlatformId.toString());
4393             }
4394             if (olePlatformRecordDocument.getName().length() < 40) {
4395                 olePlatformRecordDocument.getDocumentHeader().setDocumentDescription(olePlatformRecordDocument.getName());
4396             } else {
4397                 String documentDescription = olePlatformRecordDocument.getName().substring(0, 39);
4398                 olePlatformRecordDocument.getDocumentHeader().setDocumentDescription(documentDescription);
4399             }
4400             olePlatformRecordDocument.setGokbId(gokbPlatformId);
4401             if (StringUtils.isNotBlank(softwarePlatform)) {
4402                 olePlatformRecordDocument.setSoftware(softwarePlatform);
4403             }
4404             if (StringUtils.isNotBlank(platformStatus)) {
4405                 String platformStatusId = getPlatformStatusId(platformStatus);
4406                 if (platformStatusId != null) {
4407                     olePlatformRecordDocument.setStatusId(platformStatusId);
4408                 } else {
4409                     olePlatformRecordDocument.setStatusId("1");
4410                 }
4411             } else {
4412                 olePlatformRecordDocument.setStatusId("1");
4413             }
4414             if (platformProviderId != null) {
4415                 setPlatformProviderDetails(platformProviderId, olePlatformRecordDocument);
4416             }
4417             OLEPlatformEventLog platformEventLog = new OLEPlatformEventLog();
4418             platformEventLog.setSaveFlag(true);
4419             platformEventLog.setLogTypeId("3");
4420             platformEventLog.setEventReportedDate(new java.sql.Date(System.currentTimeMillis()));
4421             platformEventLog.setEventUserId(GlobalVariables.getUserSession().getPrincipalId());
4422             platformEventLog.setEventNote("Platform Record is created through Gokb import");
4423             olePlatformRecordDocument.getEventLogs().add(platformEventLog);
4424             olePlatformRecordDocument = (OLEPlatformRecordDocument) KRADServiceLocatorWeb.getDocumentService().saveDocument(olePlatformRecordDocument);
4425             return olePlatformRecordDocument;
4426         } catch (Exception e) {
4427             LOG.error("Exception while saving Platform Record through E-Resource" + e);
4428         }
4429         return null;
4430     }
4431 
4432     public void updatePlatform(OLEPlatformRecordDocument olePlatformRecordDocument, String platformName, String platformStatus, String softwarePlatform, Integer platformProviderId) {
4433         if (StringUtils.isNotBlank(platformName)) {
4434             olePlatformRecordDocument.setName(platformName);
4435         }
4436         if (StringUtils.isNotBlank(platformStatus)) {
4437             String platformStatusId = getPlatformStatusId(platformStatus);
4438             if (platformStatusId != null) {
4439                 olePlatformRecordDocument.setStatusId(platformStatusId);
4440             }
4441         }
4442         if (StringUtils.isNotBlank(softwarePlatform)) {
4443             olePlatformRecordDocument.setSoftware(softwarePlatform);
4444         }
4445         if (platformProviderId != null) {
4446             setPlatformProviderDetails(platformProviderId, olePlatformRecordDocument);
4447         }
4448         OLEPlatformEventLog platformEventLog = new OLEPlatformEventLog();
4449         platformEventLog.setSaveFlag(true);
4450         platformEventLog.setLogTypeId("3");
4451         platformEventLog.setEventReportedDate(new java.sql.Date(System.currentTimeMillis()));
4452         platformEventLog.setEventUserId(GlobalVariables.getUserSession().getPrincipalId());
4453         platformEventLog.setEventNote("Platform Record is Updated through Gokb import");
4454         olePlatformRecordDocument.getEventLogs().add(platformEventLog);
4455         KRADServiceLocatorWeb.getDocumentService().updateDocument(olePlatformRecordDocument);
4456         //TODO searchable
4457     }
4458 
4459     public void updatePublisher(List<OLEGOKbTIPP> oleGoKbTIPPList, OLEEResourceRecordDocument oleeResourceRecordDocument) {
4460         if (oleGoKbTIPPList != null && oleGoKbTIPPList.size() > 0) {
4461             OLEGOKbTIPP oleGoKbTIPP = oleGoKbTIPPList.get(0);
4462             if (oleGoKbTIPP != null && oleGoKbTIPP.getPublisherId() != null) {
4463                 updatePublisherDetails(oleeResourceRecordDocument, oleGoKbTIPP.getPublisherId());
4464             }
4465         }
4466     }
4467 
4468     public void updatePublisherDetails(OLEEResourceRecordDocument oleeResourceRecordDocument, Integer publisherId) {
4469         OleGokbOrganization oleGokbOrganization = getBusinessObjectService().findBySinglePrimaryKey(OleGokbOrganization.class, publisherId);
4470         if (oleGokbOrganization != null) {
4471             Map vendorMap = new HashMap();
4472             vendorMap.put(OLEConstants.GOKB_ID, oleGokbOrganization.getGokbOrganizationId());
4473             List<VendorDetail> vendorDetails = (List<VendorDetail>) getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
4474             if (vendorDetails != null && vendorDetails.size() > 0) {
4475                 VendorDetail vendorDetail = vendorDetails.get(0);
4476                 oleeResourceRecordDocument.setPublisherId(vendorDetail.getVendorNumber());
4477                 oleeResourceRecordDocument.setActivePublisher(vendorDetail.isActiveIndicator());
4478                 KRADServiceLocatorWeb.getDocumentService().updateDocument(oleeResourceRecordDocument);
4479             }
4480             updateEResVendorAssociation(oleeResourceRecordDocument);
4481         }
4482     }
4483 
4484     public void updatePlatformProvider(OLEEResourceRecordDocument oleeResourceRecordDocument) {
4485         Set<String> platform = new HashSet<>();
4486         StringBuffer platformProvider = new StringBuffer();
4487         for (OLEEResourceInstance oleEResourceInstance : oleeResourceRecordDocument.getOleERSInstances()){
4488             if (StringUtils.isNotBlank(oleEResourceInstance.getPlatformId())){
4489                 OLEPlatformRecordDocument olePlatformRecordDocument = getBusinessObjectService().findBySinglePrimaryKey(OLEPlatformRecordDocument.class,oleEResourceInstance.getPlatformId());
4490                 if (olePlatformRecordDocument!=null && !platform.contains(olePlatformRecordDocument.getName())){
4491                     platform.add(olePlatformRecordDocument.getName());
4492                     platformProvider.append(olePlatformRecordDocument.getName());
4493                     platformProvider.append(OLEConstants.COMMA);
4494                 }
4495             }
4496         }
4497         if (platformProvider.length()>0){
4498             oleeResourceRecordDocument.setPlatformProvider(platformProvider.substring(0, platformProvider.length() - 1));
4499         }
4500     }
4501 
4502     public void updateEResVendorAssociation(OLEEResourceRecordDocument oleEResourceRecordDocument){
4503         if (oleEResourceRecordDocument != null) {
4504             Map roleMap = new HashMap();
4505             roleMap.put("associatedEntityId", oleEResourceRecordDocument.getOleERSIdentifier());
4506             roleMap.put("vendorRoleId", "2");
4507             List<OLEVendorAssociation> vendorAssociations = (List<OLEVendorAssociation>) getBusinessObjectService().findMatching(OLEVendorAssociation.class, roleMap);
4508             if (!(vendorAssociations != null && vendorAssociations.size() > 0)) {
4509                 if (oleEResourceRecordDocument.getOleERSIdentifier() != null && StringUtils.isNotBlank(oleEResourceRecordDocument.getPublisherId())) {
4510                     String[] publisherDetails = oleEResourceRecordDocument.getPublisherId().split("-");
4511                     OLEVendorAssociation oleVendorAssociation = new OLEVendorAssociation();
4512                     oleVendorAssociation.setVendorHeaderGeneratedIdentifier(publisherDetails.length > 0 ? Integer.parseInt(publisherDetails[0]) : 0);
4513                     oleVendorAssociation.setVendorDetailAssignedIdentifier(publisherDetails.length > 1 ? Integer.parseInt(publisherDetails[1]) : 0);
4514                     oleVendorAssociation.setVendorRoleId("2");
4515                     oleVendorAssociation.setAssociatedEntityId(oleEResourceRecordDocument.getOleERSIdentifier());
4516                     getBusinessObjectService().save(oleVendorAssociation);
4517                 }
4518             }
4519         }
4520     }
4521 
4522     public void storeEventAttachments(MultipartFile attachmentFile) throws IOException {
4523         String location = "";
4524         location = getKualiConfigurationService().getPropertyValueAsString(
4525                 KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + OLEConstants.OleLicenseRequest.ERESOURCE_EVENT_TMP_LOCATION;
4526         LOG.info("Event Attachment LOG :" + location);
4527         File dirLocation = new File(location);
4528         if (!dirLocation.exists()) {
4529             boolean success = dirLocation.mkdirs();
4530             if (!success) {
4531                 LOG.error("Could not generate directory for File at: " + dirLocation.getAbsolutePath());
4532             }
4533         }
4534         location = location + File.separator + attachmentFile.getOriginalFilename();
4535         InputStream fileContents = attachmentFile.getInputStream();
4536         File fileOut = new File(location);
4537         FileOutputStream streamOut = null;
4538         BufferedOutputStream bufferedStreamOut = null;
4539         try {
4540             streamOut = new FileOutputStream(fileOut);
4541             bufferedStreamOut = new BufferedOutputStream(streamOut);
4542             int c;
4543             while ((c = fileContents.read()) != -1) {
4544                 bufferedStreamOut.write(c);
4545             }
4546         } finally {
4547             bufferedStreamOut.close();
4548             streamOut.close();
4549         }
4550     }
4551 
4552     public void processEventAttachments(List<OLEEResourceEventLog> oleEResourceEventLogs) {
4553         LOG.debug("Inside processEventAttachments method");
4554         List<OLEEResourceEventLog> eventAttachments = new ArrayList<OLEEResourceEventLog>();
4555         if (oleEResourceEventLogs.size() > 0) {
4556             try {
4557                 String location = "";
4558                 location = getKualiConfigurationService().getPropertyValueAsString(
4559                         KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + OLEConstants.OleLicenseRequest.ERESOURCE_EVENT_TMP_LOCATION;
4560                 LOG.info("Event Attachment LOG :" + location);
4561                 for (OLEEResourceEventLog oleEResourceEventLog : oleEResourceEventLogs) {
4562                     if (StringUtils.isNotBlank(oleEResourceEventLog.getAttachmentFileName1())) {
4563                         File file = new File(location + File.separator + oleEResourceEventLog.getAttachmentFileName1());
4564                         oleEResourceEventLog.setAttachmentContent1(FileUtils.readFileToByteArray(file));
4565                     }
4566                     if (StringUtils.isNotBlank(oleEResourceEventLog.getAttachmentFileName2())) {
4567                         File file = new File(location + File.separator + oleEResourceEventLog.getAttachmentFileName2());
4568                         oleEResourceEventLog.setAttachmentContent2(FileUtils.readFileToByteArray(file));
4569                     }
4570                 }
4571                 for (OLEEResourceEventLog oleEResourceEventLog : oleEResourceEventLogs) {
4572                     if (StringUtils.isNotBlank(oleEResourceEventLog.getAttachmentFileName1())) {
4573                         File file = new File(location + File.separator + oleEResourceEventLog.getAttachmentFileName1());
4574                         file.delete();
4575                     }
4576                     if (StringUtils.isNotBlank(oleEResourceEventLog.getAttachmentFileName2())) {
4577                         File file = new File(location + File.separator + oleEResourceEventLog.getAttachmentFileName2());
4578                         file.delete();
4579                     }
4580                 }
4581             } catch (Exception e) {
4582                 LOG.error("Exception while saving attachment" + e);
4583             }
4584 
4585         }
4586     }
4587 
4588     public boolean addAttachmentFile(OLEEResourceEventLog oleEResourceEventLog, String sectionId) {
4589         boolean validFile = true;
4590         MultipartFile attachmentFile1 = oleEResourceEventLog.getAttachmentFile1();
4591         if (attachmentFile1 != null && !org.apache.commons.lang.StringUtils.isBlank(attachmentFile1.getOriginalFilename())) {
4592             if (attachmentFile1.getSize() == 0) {
4593                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(sectionId,
4594                         RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile1.getOriginalFilename());
4595                 validFile = false;
4596             } else {
4597                 try {
4598                     oleEResourceEventLog.setAttachmentFileName1(attachmentFile1.getOriginalFilename());
4599                     oleEResourceEventLog.setAttachmentMimeType1(attachmentFile1.getContentType());
4600                     storeEventAttachments(attachmentFile1);
4601                 } catch (Exception e) {
4602                     LOG.error("Exception while storing the Attachment Document" + e);
4603                 }
4604             }
4605         }
4606         MultipartFile attachmentFile2 = oleEResourceEventLog.getAttachmentFile2();
4607         if (attachmentFile2 != null && !org.apache.commons.lang.StringUtils.isBlank(attachmentFile2.getOriginalFilename())) {
4608             if (attachmentFile2.getSize() == 0) {
4609                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(sectionId,
4610                         RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile2.getOriginalFilename());
4611                 validFile = false;
4612             } else {
4613                 try {
4614                     oleEResourceEventLog.setAttachmentFileName2(attachmentFile2.getOriginalFilename());
4615                     oleEResourceEventLog.setAttachmentMimeType2(attachmentFile2.getContentType());
4616                     storeEventAttachments(attachmentFile2);
4617                 } catch (Exception e) {
4618                     LOG.error("Exception while storing the Attachment Document" + e);
4619                 }
4620             }
4621         }
4622         return validFile;
4623     }
4624 
4625     public void downloadAttachment(HttpServletResponse response, String eventLogId, String fileName, byte[] attachmentContent, String attachmentMimeType) throws Exception {
4626         File file;
4627         String location = "";
4628         location = getKualiConfigurationService().getPropertyValueAsString(
4629                 KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + OLEConstants.OleLicenseRequest.ERESOURCE_EVENT_TMP_LOCATION;
4630         if (eventLogId == null) {
4631             file = new File(getKualiConfigurationService().getPropertyValueAsString(
4632                     KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + OLEConstants.OleLicenseRequest.ERESOURCE_EVENT_TMP_LOCATION +
4633                     File.separator + fileName);
4634             LOG.info("Uploaded file location : " + file.getAbsolutePath());
4635         } else {
4636             file = new File(location + File.separator + fileName);
4637             FileUtils.writeByteArrayToFile(file, attachmentContent);
4638         }
4639         response.setContentType(attachmentMimeType);
4640         response.setContentLength((int) file.length());
4641         response.setHeader("Expires", "0");
4642         response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
4643         response.setHeader("Pragma", "public");
4644         response.setHeader("Content-Disposition",
4645                 "attachment; filename=\"" + fileName + "\"");
4646         InputStream fis = new BufferedInputStream(new FileInputStream(file));
4647         FileCopyUtils.copy(fis, response.getOutputStream());
4648     }
4649 
4650     private String convertDateFormatToRegex(String format){
4651         format = format.replace("\\", "\\\\").replace(".", "\\.").replace("-", "\\-").replace("+", "\\+").replace("(",
4652                 "\\(").replace(")", "\\)").replace("[", "\\[").replace("]", "\\]").replace("|", "\\|").replace("yyyy",
4653                 "((1|2)[0-9]{3})").replace("yy", "([0-9]{2})").replaceAll("M{4,}",
4654                 "([@]+)") //"(January|February|March|April|May|June|July|August|September|October|November|December)")
4655                 .replace("MMM", "([@]{3})") //"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)")
4656                 .replace("MM", "(0[1-9]|1[012])").replace("M", "(0?[1-9]|1[012])").replace("dd",
4657                         "(0[1-9]|[12][0-9]|3[01])").replace("d", "(0?[1-9]|[12][0-9]|3[01])").replace("hh",
4658                         "(1[0-2]|0[1-9])").replace("h", "(1[0-2]|0?[1-9])").replace("HH", "(2[0-3]|1[0-9]|0[0-9])")
4659                 .replace("H", "(2[0-3]|1[0-9]|0?[0-9])").replace("kk", "(2[0-4]|1[0-9]|0[1-9])").replace("k",
4660                         "(2[0-4]|1[0-9]|0?[1-9])").replace("KK", "(1[01]|0[0-9])").replace("K", "(1[01]|0?[0-9])")
4661                 .replace("mm", "([0-5][0-9])").replace("m", "([1-5][0-9]|0?[0-9])").replace("ss", "([0-5][0-9])")
4662                 .replace("s", "([1-5][0-9]|0?[0-9])").replace("SSS", "([0-9][0-9][0-9])").replace("SS",
4663                         "([0-9][0-9][0-9]?)").replace("S", "([0-9][0-9]?[0-9]?)").replaceAll("E{4,}",
4664                         "([@]+)")//"(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)")
4665                 .replaceAll("E{1,3}", "([@]{3})")//"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)")
4666                 .replace("DDD", "(3[0-6][0-5]|[1-2][0-9][0-9]|0[0-9][1-9])").replace("DD",
4667                         "(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9][1-9])").replace("D",
4668                         "(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9]?[1-9])").replace("F", "([1-5])").replace("ww",
4669                         "(5[0-3]|[1-4][0-9]|0[1-9])").replace("w", "(5[0-3]|[1-4][0-9]|[1-9])").replace("W", "([1-5])")
4670                 .replaceAll("z{4,}", "([@]+)").replaceAll("z{1,3}", "([@]{1,4})").replaceAll("a{1,}", "([aApP][mM])")
4671                 .replaceAll("G{1,}", "([aA][dD]|[bB][cC])").replace(" ", "\\s").replace("@", "a-zA-Z");
4672 
4673         return format;
4674 
4675     }
4676     public OLEEResourceRecordDocument populateInstanceAndEInstance(OLEEResourceRecordDocument oleeResourceRecordDocument){
4677         if (oleeResourceRecordDocument.getOleERSIdentifier() != null) {
4678             Map ids = new HashMap();
4679             ids.put("oleERSIdentifier", oleeResourceRecordDocument.getOleERSIdentifier());
4680             List<OLEEResourceInstance> oleeResourceInstances = (List<OLEEResourceInstance>) getBusinessObjectService().findMatching(OLEEResourceInstance.class, ids);
4681             oleeResourceRecordDocument.geteRSInstances().clear();
4682             oleeResourceRecordDocument.geteRSInstances().addAll(oleeResourceInstances);
4683             oleeResourceRecordDocument.setOleERSInstances(oleeResourceInstances);
4684             ids = new HashMap();
4685             List<OLEEResourceInstance> linkedResourceInstances = new ArrayList<>();
4686             for (OLELinkedEresource linkedEresource : oleeResourceRecordDocument.getOleLinkedEresources()) {
4687                 if (linkedEresource.getRelationShipType().equalsIgnoreCase("child")) {
4688                     ids.put("oleERSIdentifier", linkedEresource.getLinkedERSIdentifier());
4689                     linkedResourceInstances.addAll(getBusinessObjectService().findMatching(OLEEResourceInstance.class, ids));
4690                     for (OLEEResourceLicense oleeResourceLicense : linkedEresource.getOleeResourceRecordDocument().getOleERSLicenseRequests()) {
4691                         oleeResourceRecordDocument.getOleERSLicenseRequests().add(oleeResourceLicense);
4692                     }
4693                 }
4694             }
4695             oleeResourceRecordDocument.geteRSInstances().addAll(linkedResourceInstances);
4696         }
4697         return oleeResourceRecordDocument;
4698     }
4699 
4700 
4701 
4702     public UniversityDateService getUniversityDateService() {
4703         if(universityDateService == null) {
4704             universityDateService = SpringContext.getBean(UniversityDateService.class);
4705         }
4706         return universityDateService;
4707     }
4708 }