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