7327d30827005d1d2bcdb97582c642ce903902fc
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.vendorlicense.impl;
18
19 import org.apache.commons.collections.CollectionUtils;
20 import org.openecomp.core.util.UniqueValueUtil;
21 import org.openecomp.core.utilities.CommonMethods;
22 import org.openecomp.sdc.common.errors.CoreException;
23 import org.openecomp.sdc.common.errors.ErrorCode;
24 import org.openecomp.sdc.datatypes.error.ErrorLevel;
25 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
26 import org.openecomp.sdc.logging.types.LoggerConstants;
27 import org.openecomp.sdc.logging.types.LoggerErrorCode;
28 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
29 import org.openecomp.sdc.logging.types.LoggerServiceName;
30 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
31 import org.openecomp.sdc.vendorlicense.VendorLicenseConstants;
32 import org.openecomp.sdc.vendorlicense.VendorLicenseManager;
33 import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao;
34 import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao;
35 import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao;
36 import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao;
37 import org.openecomp.sdc.vendorlicense.dao.LimitDao;
38 import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao;
39 import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity;
40 import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity;
41 import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel;
42 import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity;
43 import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementModel;
44 import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity;
45 import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity;
46 import org.openecomp.sdc.vendorlicense.dao.types.LimitType;
47 import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity;
48 import org.openecomp.sdc.vendorlicense.errors.InvalidDateErrorBuilder;
49 import org.openecomp.sdc.vendorlicense.errors.LimitErrorBuilder;
50 import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
51 import org.openecomp.sdc.versioning.VersioningUtil;
52 import org.openecomp.sdc.versioning.dao.types.Version;
53
54 import java.time.LocalDate;
55 import java.time.format.DateTimeFormatter;
56 import java.util.Collection;
57 import java.util.Objects;
58 import java.util.Optional;
59 import java.util.Set;
60
61 public class VendorLicenseManagerImpl implements VendorLicenseManager {
62   private VendorLicenseFacade vendorLicenseFacade;
63   private VendorLicenseModelDao vendorLicenseModelDao;
64   private LicenseAgreementDao licenseAgreementDao;
65   private FeatureGroupDao featureGroupDao;
66   private EntitlementPoolDao entitlementPoolDao;
67   private LicenseKeyGroupDao licenseKeyGroupDao;
68   private LimitDao limitDao;
69   private static final String VLM_ID = "VLM id";
70   private static final String EP_LKGID = "EP/LKGId";
71   private static final String VLM_ID_LKG_ID = "VLM id, LKG id";
72   private static final String VLM_ID_LA_ID = "VLM id, LA id";
73   private static final String VLM_ID_FG_ID = "VLM id, FG id";
74   private static final String VLM_ID_EP_ID = "VLM id, EP id";
75   private static final String EP_POOL_START_TIME = "T00:00:00Z";
76   private static final String EP_POOL_EXPIRY_TIME = "T23:59:59Z";
77   private static final  DateTimeFormatter FORMATTER
78           = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'");
79   public VendorLicenseManagerImpl(VendorLicenseFacade vendorLicenseFacade,
80                                   VendorLicenseModelDao vendorLicenseModelDao,
81                                   LicenseAgreementDao licenseAgreementDao,
82                                   FeatureGroupDao featureGroupDao,
83                                   EntitlementPoolDao entitlementPoolDao,
84                                   LicenseKeyGroupDao licenseKeyGroupDao,
85                                   LimitDao limitDao) {
86     this.vendorLicenseFacade = vendorLicenseFacade;
87     this.vendorLicenseModelDao = vendorLicenseModelDao;
88     this.licenseAgreementDao = licenseAgreementDao;
89     this.featureGroupDao = featureGroupDao;
90     this.entitlementPoolDao = entitlementPoolDao;
91     this.licenseKeyGroupDao = licenseKeyGroupDao;
92     this.limitDao = limitDao;
93   }
94
95
96   @Override
97   public void validate(String vendorLicenseModelId, Version version) {
98     vendorLicenseFacade.validate(vendorLicenseModelId, version);
99   }
100
101   @Override
102   public VendorLicenseModelEntity createVendorLicenseModel(
103       VendorLicenseModelEntity vendorLicenseModelEntity) {
104     vendorLicenseModelDao.create(vendorLicenseModelEntity);
105     return vendorLicenseModelEntity;
106   }
107
108   @Override
109   public void updateVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity) {
110     String existingVendorName = vendorLicenseModelDao.get(vendorLicenseModelEntity).getVendorName();
111
112     updateUniqueName(VendorLicenseConstants.UniqueValues.VENDOR_NAME, existingVendorName,
113         vendorLicenseModelEntity.getVendorName());
114     vendorLicenseModelDao.update(vendorLicenseModelEntity);
115   }
116
117   @Override
118   public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) {
119     return vendorLicenseFacade.getVendorLicenseModel(vlmId, version);
120   }
121
122   @Override
123   public void deleteVendorLicenseModel(String vlmId, Version version) {
124     MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
125         LoggerTragetServiceName.DELETE_ENTITY, ErrorLevel.ERROR.name(),
126         LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION);
127     throw new UnsupportedOperationException(VendorLicenseConstants.UNSUPPORTED_OPERATION_ERROR);
128   }
129
130   @Override
131   public Collection<LicenseAgreementEntity> listLicenseAgreements(String vlmId, Version version) {
132     return licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, version, null));
133   }
134
135   @Override
136   public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) {
137     return vendorLicenseFacade.createLicenseAgreement(licenseAgreement);
138   }
139
140   @Override
141   public void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement,
142                                      Set<String> addedFeatureGroupIds,
143                                      Set<String> removedFeatureGroupIds) {
144     LicenseAgreementEntity retrieved = licenseAgreementDao.get(licenseAgreement);
145     VersioningUtil
146         .validateEntityExistence(retrieved, licenseAgreement, VendorLicenseModelEntity.ENTITY_TYPE);
147     VersioningUtil.validateContainedEntitiesExistence(new FeatureGroupEntity().getEntityType(),
148         removedFeatureGroupIds, retrieved, retrieved.getFeatureGroupIds());
149     VersioningUtil.validateEntitiesExistence(addedFeatureGroupIds,
150         new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(),
151             licenseAgreement.getVersion(),
152             null),
153         featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE);
154
155     updateUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME,
156         retrieved.getName(), licenseAgreement.getName(), licenseAgreement.getVendorLicenseModelId(),
157         licenseAgreement.getVersion().getId());
158     licenseAgreementDao.updateColumnsAndDeltaFeatureGroupIds(licenseAgreement, addedFeatureGroupIds,
159         removedFeatureGroupIds);
160
161     addFeatureGroupsToLicenseAgreementRef(addedFeatureGroupIds, licenseAgreement);
162     removeFeatureGroupsToLicenseAgreementRef(removedFeatureGroupIds, licenseAgreement);
163   }
164
165   @Override
166   public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version,
167                                                         String licenseAgreementId) {
168     return vendorLicenseFacade.getLicenseAgreementModel(vlmId, version, licenseAgreementId);
169   }
170
171   @Override
172   public void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId) {
173     LicenseAgreementEntity input =
174         new LicenseAgreementEntity(vlmId, version, licenseAgreementId);
175     LicenseAgreementEntity retrieved = licenseAgreementDao.get(input);
176     VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE);
177
178     removeFeatureGroupsToLicenseAgreementRef(retrieved.getFeatureGroupIds(), retrieved);
179
180     licenseAgreementDao.delete(retrieved);
181
182     deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME,
183         retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(),
184         retrieved.getName());
185   }
186
187   @Override
188   public Collection<FeatureGroupEntity> listFeatureGroups(String vlmId, Version version) {
189     return vendorLicenseFacade.listFeatureGroups(vlmId, version);
190   }
191
192   @Override
193   public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) {
194     return vendorLicenseFacade.createFeatureGroup(featureGroup);
195   }
196
197   @Override
198   public void updateFeatureGroup(FeatureGroupEntity featureGroup,
199                                  Set<String> addedLicenseKeyGroups,
200                                  Set<String> removedLicenseKeyGroups,
201                                  Set<String> addedEntitlementPools,
202                                  Set<String> removedEntitlementPools) {
203     FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup);
204     VersioningUtil
205         .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE);
206
207     VersioningUtil.validateContainedEntitiesExistence(new LicenseKeyGroupEntity().getEntityType(),
208         removedLicenseKeyGroups, retrieved, retrieved.getLicenseKeyGroupIds());
209     VersioningUtil.validateContainedEntitiesExistence(new EntitlementPoolEntity().getEntityType(),
210         removedEntitlementPools, retrieved, retrieved.getEntitlementPoolIds());
211
212     VersioningUtil.validateEntitiesExistence(addedLicenseKeyGroups,
213         new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(),
214             null),
215         licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE);
216     VersioningUtil.validateEntitiesExistence(addedEntitlementPools,
217         new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(),
218             null),
219         entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE);
220
221     updateUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME,
222         retrieved.getName(), featureGroup.getName(), featureGroup.getVendorLicenseModelId(),
223         featureGroup.getVersion().getId());
224
225     addLicenseKeyGroupsToFeatureGroupsRef(addedLicenseKeyGroups, featureGroup);
226     removeLicenseKeyGroupsToFeatureGroupsRef(removedLicenseKeyGroups, featureGroup);
227     addEntitlementPoolsToFeatureGroupsRef(addedEntitlementPools, featureGroup);
228     removeEntitlementPoolsToFeatureGroupsRef(removedEntitlementPools, featureGroup);
229
230     featureGroupDao.updateFeatureGroup(featureGroup, addedEntitlementPools, removedEntitlementPools,
231         addedLicenseKeyGroups, removedLicenseKeyGroups);
232
233     updateEpLkgOnMrnChange(featureGroup, addedLicenseKeyGroups, addedEntitlementPools, retrieved);
234   }
235
236   /**
237    * If MRN is updated in feature group then update all linked EPs and Lkgs with new versionUuId
238    * @param featureGroup - Feature Group entity which is requested for update
239    * @param addedLicenseKeyGroups - LicenseKeyGroups added with Feature Group
240    * @param addedEntitlementPools - EntitlementPools added with Feature Group
241    * @param retrieved - Feature Group entity fetched from database
242    */
243   private void updateEpLkgOnMrnChange(FeatureGroupEntity featureGroup,
244                                       Set<String> addedLicenseKeyGroups,
245                                       Set<String> addedEntitlementPools,
246                                       FeatureGroupEntity retrieved) {
247     if (Objects.nonNull(retrieved.getManufacturerReferenceNumber())
248         && !retrieved.getManufacturerReferenceNumber().equals(featureGroup
249         .getManufacturerReferenceNumber())) {
250       if (CollectionUtils.isEmpty(addedEntitlementPools)) {
251         updateEntitlementPool(featureGroup, retrieved.getEntitlementPoolIds());
252       } else {
253         updateEntitlementPool(featureGroup, addedEntitlementPools);
254       }
255
256       if (CollectionUtils.isEmpty(addedLicenseKeyGroups)) {
257         updateLicenseKeyGroup(featureGroup, retrieved.getLicenseKeyGroupIds());
258       } else {
259         updateLicenseKeyGroup(featureGroup, addedLicenseKeyGroups);
260       }
261     }
262   }
263
264   private void updateEntitlementPool(FeatureGroupEntity featureGroup,
265                                      Set<String> entitlementPoolIds) {
266     for (String epId: entitlementPoolIds) {
267       final EntitlementPoolEntity entitlementPoolEntity = entitlementPoolDao
268           .get(new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup
269               .getVersion(), epId));
270       if (Objects.nonNull(entitlementPoolEntity)) {
271         entitlementPoolEntity.setVersionUuId(CommonMethods.nextUuId());
272         entitlementPoolDao.update(entitlementPoolEntity);
273       }
274     }
275   }
276
277   private void updateLicenseKeyGroup(FeatureGroupEntity featureGroup,
278                                      Set<String> licenseKeyGroupIds) {
279     for (String lkgId: licenseKeyGroupIds) {
280       final LicenseKeyGroupEntity licenseKeyGroupEntity = licenseKeyGroupDao
281           .get(new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(),
282               featureGroup.getVersion(), lkgId));
283       if (Objects.nonNull(licenseKeyGroupEntity)) {
284         licenseKeyGroupEntity.setVersionUuId(CommonMethods.nextUuId());
285         licenseKeyGroupDao.update(licenseKeyGroupEntity);
286       }
287     }
288   }
289
290   @Override
291   public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) {
292     return vendorLicenseFacade.getFeatureGroupModel(featureGroup);
293   }
294
295   @Override
296   public void deleteFeatureGroup(FeatureGroupEntity featureGroup) {
297     FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup);
298     VersioningUtil
299         .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE);
300
301     removeLicenseKeyGroupsToFeatureGroupsRef(retrieved.getLicenseKeyGroupIds(), featureGroup);
302     removeEntitlementPoolsToFeatureGroupsRef(retrieved.getEntitlementPoolIds(), featureGroup);
303
304     for (String licenceAgreementId : retrieved.getReferencingLicenseAgreements()) {
305       licenseAgreementDao.removeFeatureGroup(
306           new LicenseAgreementEntity(featureGroup.getVendorLicenseModelId(),
307               featureGroup.getVersion(),
308               licenceAgreementId), featureGroup.getId());
309     }
310
311     featureGroupDao.delete(featureGroup);
312
313     deleteUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME,
314         retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(),
315         retrieved.getName());
316   }
317
318   @Override
319   public Collection<EntitlementPoolEntity> listEntitlementPools(String vlmId, Version version) {
320     return vendorLicenseFacade.listEntitlementPools(vlmId, version);
321   }
322
323   @Override
324   public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) {
325     entitlementPool.setStartDate(entitlementPool.getStartDate() != null ? (entitlementPool
326         .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate() + EP_POOL_START_TIME
327         : null) : null);
328     entitlementPool.setExpiryDate(entitlementPool.getExpiryDate() != null ? (entitlementPool
329         .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate() + EP_POOL_EXPIRY_TIME 
330         : null) : null);
331
332     validateCreateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(),
333         entitlementPool.getVendorLicenseModelId());
334     return vendorLicenseFacade.createEntitlementPool(entitlementPool);
335   }
336
337   private void validateCreateDate(String startDate, String expiryDate,
338                                   String vendorLicenseModelId) {
339   LocalDate parsedStartDate = parseLocalDate(startDate);
340   LocalDate parsedExpiryDate = parseLocalDate(expiryDate);
341
342
343     validateIfStartAndExpiryDateIsNotNull(startDate, expiryDate,
344             vendorLicenseModelId, parsedStartDate, parsedExpiryDate);
345
346     if (startDate != null && expiryDate == null
347                       && parsedStartDate.atStartOfDay().isBefore
348           (LocalDate.now().atStartOfDay())) {
349         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
350             LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(),
351             LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE);
352         throw new CoreException(
353             new InvalidDateErrorBuilder(vendorLicenseModelId)
354                 .build());
355     }
356
357     if (startDate == null && expiryDate != null) {
358       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
359           LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(),
360           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE);
361       throw new CoreException(
362           new InvalidDateErrorBuilder(vendorLicenseModelId)
363               .build());
364
365     }
366   }
367
368   private void validateIfStartAndExpiryDateIsNotNull(String startDate, String expiryDate,
369                                                      String vendorLicenseModelId,
370                                                      LocalDate parsedStartDate,
371                                                      LocalDate parsedExpiryDate) {
372     if (startDate != null && expiryDate != null
373             && isValidatStartAndExpiryDate(parsedStartDate, parsedExpiryDate)) {
374       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
375               LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(),
376               LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE);
377       throw new CoreException(
378               new InvalidDateErrorBuilder(vendorLicenseModelId)
379                       .build());
380     }
381   }
382
383   private boolean isValidatStartAndExpiryDate(LocalDate parsedStartDate,
384                                               LocalDate parsedExpiryDate) {
385     return parsedStartDate.atStartOfDay().isBefore(LocalDate.now().atStartOfDay())
386     || parsedExpiryDate.atStartOfDay().isEqual(parsedStartDate.atStartOfDay())
387     || parsedExpiryDate.isBefore(parsedStartDate);
388   }
389
390   private static LocalDate parseLocalDate(String date) {
391     if (date == null || date.isEmpty()) {
392       return null;
393     }
394
395     return LocalDate.parse(date, FORMATTER );
396   }
397
398   private void validateUpdateDate(String startDate, String expiryDate,
399                                   String vendorLicenseModelId) {
400     LocalDate parsedStartDate = parseLocalDate(startDate);
401     LocalDate parsedExpiryDate = parseLocalDate(expiryDate);
402
403     if (startDate != null && expiryDate != null
404             && (parsedExpiryDate.atStartOfDay()
405             .isEqual(parsedStartDate.atStartOfDay())
406             || parsedExpiryDate.isBefore(parsedStartDate ))) {
407       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
408               LoggerTragetServiceName.VALIDATE_DATE_RANGE,ErrorLevel.ERROR.name(),
409               LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE);
410       throw new CoreException(
411               new InvalidDateErrorBuilder(vendorLicenseModelId)
412                       .build());
413     }
414
415     if (startDate == null && expiryDate != null) {
416       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
417           LoggerTragetServiceName.VALIDATE_DATE_RANGE, ErrorLevel.ERROR.name(),
418           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VALUE);
419       throw new CoreException(
420           new InvalidDateErrorBuilder(vendorLicenseModelId)
421               .build());
422
423     }
424   }
425
426   @Override
427   public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) {
428     entitlementPool.setStartDate(entitlementPool.getStartDate() != null ? (entitlementPool
429         .getStartDate().trim().length() != 0 ? entitlementPool.getStartDate() + EP_POOL_START_TIME
430         : null) : null);
431     entitlementPool.setExpiryDate(entitlementPool.getExpiryDate() != null ? (entitlementPool
432         .getExpiryDate().trim().length() != 0 ? entitlementPool.getExpiryDate() + EP_POOL_EXPIRY_TIME 
433         : null) : null);
434
435     validateUpdateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(),
436         entitlementPool.getVendorLicenseModelId());
437     vendorLicenseFacade.updateEntitlementPool(entitlementPool);
438   }
439
440   @Override
441   public EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool) {
442     EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool);
443     VersioningUtil
444         .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE);
445     DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
446     if (retrieved.getStartDate() != null) {
447       retrieved.setStartDate(LocalDate.parse(retrieved.getStartDate(), FORMATTER ).format
448           (targetFormatter));
449     }
450
451     if (retrieved.getExpiryDate() != null) {
452       retrieved.setExpiryDate(LocalDate.parse(retrieved.getExpiryDate(), FORMATTER ).format
453           (targetFormatter));
454     }
455     return retrieved;
456   }
457
458   @Override
459   public void deleteEntitlementPool(EntitlementPoolEntity entitlementPool) {
460     EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool);
461     VersioningUtil
462         .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE);
463
464     for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) {
465       featureGroupDao.removeEntitlementPool(
466           new FeatureGroupEntity(entitlementPool.getVendorLicenseModelId(),
467               entitlementPool.getVersion(),
468               referencingFeatureGroupId), entitlementPool.getId());
469     }
470
471     deleteChildLimits(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(),
472         entitlementPool.getId());
473
474     entitlementPoolDao.delete(entitlementPool);
475
476     deleteUniqueName(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME,
477         retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(),
478         retrieved.getName());
479   }
480
481   protected void deleteChildLimits(String vlmId, Version version, String epLkgId) {
482     Optional<Collection<LimitEntity>> limitEntities = Optional.ofNullable(
483         listLimits(vlmId, version, epLkgId));
484     limitEntities.ifPresent(entities -> entities.forEach(this::deleteLimit));
485   }
486
487   @Override
488   public Collection<LicenseKeyGroupEntity> listLicenseKeyGroups(String vlmId, Version version) {
489     return vendorLicenseFacade.listLicenseKeyGroups(vlmId, version);
490   }
491
492   @Override
493   public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) {
494     licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup
495         .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + EP_POOL_START_TIME
496         : null) : null);
497     licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup
498         .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + EP_POOL_EXPIRY_TIME 
499         : null) : null);
500
501     validateCreateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(),
502         licenseKeyGroup.getVendorLicenseModelId());
503     return vendorLicenseFacade.createLicenseKeyGroup(licenseKeyGroup);
504   }
505
506   @Override
507   public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) {
508     licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup
509         .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + EP_POOL_START_TIME
510         : null) : null);
511     licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup
512         .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + EP_POOL_EXPIRY_TIME 
513         : null) : null);
514
515     validateUpdateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(),
516         licenseKeyGroup.getVendorLicenseModelId());
517     vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroup);
518   }
519
520   @Override
521   public LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) {
522     LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup);
523     VersioningUtil
524         .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE);
525     return retrieved;
526   }
527
528   @Override
529   public void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) {
530     LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup);
531     VersioningUtil
532         .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE);
533
534     for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) {
535       featureGroupDao.removeLicenseKeyGroup(
536           new FeatureGroupEntity(licenseKeyGroup.getVendorLicenseModelId(),
537               licenseKeyGroup.getVersion(),
538               referencingFeatureGroupId), licenseKeyGroup.getId());
539     }
540
541     deleteChildLimits(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(),
542         licenseKeyGroup.getId());
543
544     licenseKeyGroupDao.delete(licenseKeyGroup);
545
546     deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME,
547         retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(),
548         retrieved.getName());
549   }
550
551   @Override
552   public LimitEntity createLimit(LimitEntity limit) {
553     validateLimit(limit);
554     LimitEntity createdLimit = vendorLicenseFacade.createLimit(limit);
555     updateParentForLimit(limit);
556     return createdLimit;
557   }
558
559   private void validateLimit(LimitEntity limit) {
560     Collection<LimitEntity> limitList =
561         listLimits(limit.getVendorLicenseModelId(), limit.getVersion()
562             , limit.getEpLkgId());
563
564     if (!isLimitNameUnique(limitList, limit.getName(), limit.getType(), limit.getId())) {
565       final ErrorCode duplicateLimitNameErrorBuilder =
566           LimitErrorBuilder.getDuplicateNameErrorbuilder(limit.getName(), limit.getType().name());
567       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
568           LoggerServiceName.Create_LIMIT.toString(), ErrorLevel.ERROR.name(),
569           LoggerErrorCode.DATA_ERROR.getErrorCode(),
570           duplicateLimitNameErrorBuilder.message());
571       throw new CoreException(duplicateLimitNameErrorBuilder);
572     }
573   }
574
575   private boolean isLimitNameUnique(Collection<LimitEntity> limitList, String name, LimitType
576       type, String id) {
577     for (LimitEntity limit : limitList) {
578       if (limit.getName().equalsIgnoreCase(name) &&
579           limit.getType().name().equalsIgnoreCase(type.name())) {
580         if (id != null && limit.getId().equals(id)) {
581           continue;
582         }
583         return false;
584       }
585     }
586     return true;
587   }
588
589   @Override
590   public Collection<LimitEntity> listLimits(String vlmId, Version version, String epLkgId) {
591     return vendorLicenseFacade.listLimits(vlmId, version, epLkgId);
592   }
593
594   @Override
595   public void deleteLimit(LimitEntity limitEntity) {
596     if (!isLimitPresent(limitEntity)) {
597       VersioningUtil
598           .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE);
599     }
600     LimitEntity retrieved = limitDao.get(limitEntity);
601     VersioningUtil
602         .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE);
603
604     limitDao.delete(limitEntity);
605
606     updateParentForLimit(limitEntity);
607   }
608
609   @Override
610   public void updateLimit(LimitEntity limit) {
611     getLimit(limit);
612     validateLimit(limit);
613     vendorLicenseFacade.updateLimit(limit);
614     updateParentForLimit(limit);
615   }
616
617   private boolean isLimitPresent(LimitEntity limit) {
618     return limitDao.isLimitPresent(limit);
619   }
620
621   @Override
622   public LimitEntity getLimit(LimitEntity limitEntity) {
623     if (!isLimitPresent(limitEntity)) {
624       VersioningUtil
625           .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE);
626     }
627     LimitEntity retrieved = limitDao.get(limitEntity);
628     VersioningUtil
629         .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE);
630     return retrieved;
631   }
632
633   /**
634    * update Parent of limit (EP/LKG) versionuuid when limit is modified so that limit updates are
635    * captured in VLM XML
636    */
637   private void updateParentForLimit(LimitEntity limit) {
638     if ("EntitlementPool".equals(limit.getParent())) {
639       EntitlementPoolEntity entitlementPoolEntity =
640           entitlementPoolDao.get(new EntitlementPoolEntity(limit.getVendorLicenseModelId(),
641               limit.getVersion(), limit.getEpLkgId()));
642       vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity);
643     }
644
645     if ("LicenseKeyGroup".equals(limit.getParent())) {
646       LicenseKeyGroupEntity licenseKeyGroupEntity = licenseKeyGroupDao.get(
647           new LicenseKeyGroupEntity(limit.getVendorLicenseModelId(), limit.getVersion(),
648               limit.getEpLkgId()));
649       vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity);
650     }
651   }
652
653   protected void addFeatureGroupsToLicenseAgreementRef(Set<String> featureGroupIds,
654                                                        LicenseAgreementEntity licenseAgreement) {
655     if (featureGroupIds != null) {
656       for (String featureGroupId : featureGroupIds) {
657         featureGroupDao.addReferencingLicenseAgreement(
658             new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(),
659                 licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId());
660       }
661     }
662   }
663
664   protected void removeFeatureGroupsToLicenseAgreementRef(Set<String> featureGroupIds,
665                                                           LicenseAgreementEntity licenseAgreement) {
666     if (featureGroupIds != null) {
667       for (String featureGroupId : featureGroupIds) {
668         featureGroupDao.removeReferencingLicenseAgreement(
669             new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(),
670                 licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId());
671       }
672     }
673   }
674
675   protected void addLicenseKeyGroupsToFeatureGroupsRef(Set<String> licenseKeyGroupIds,
676                                                        FeatureGroupEntity featureGroup) {
677     if (licenseKeyGroupIds != null) {
678       for (String licenseKeyGroupId : licenseKeyGroupIds) {
679         licenseKeyGroupDao.addReferencingFeatureGroup(
680             new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(),
681                 featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId());
682       }
683     }
684   }
685
686   protected void removeLicenseKeyGroupsToFeatureGroupsRef(Set<String> licenseKeyGroupIds,
687                                                           FeatureGroupEntity featureGroup) {
688     if (licenseKeyGroupIds != null) {
689       for (String licenseKeyGroupId : licenseKeyGroupIds) {
690         licenseKeyGroupDao.removeReferencingFeatureGroup(
691             new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(),
692                 featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId());
693       }
694     }
695   }
696
697   protected void addEntitlementPoolsToFeatureGroupsRef(Set<String> entitlementPoolIds,
698                                                        FeatureGroupEntity featureGroup) {
699     if (entitlementPoolIds != null) {
700       for (String entitlementPoolId : entitlementPoolIds) {
701         entitlementPoolDao.addReferencingFeatureGroup(
702             new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(),
703                 featureGroup.getVersion(), entitlementPoolId), featureGroup.getId());
704       }
705     }
706   }
707
708   protected void removeEntitlementPoolsToFeatureGroupsRef(Set<String> entitlementPoolIds,
709                                                           FeatureGroupEntity featureGroup) {
710     if (entitlementPoolIds != null) {
711       for (String entitlementPoolId : entitlementPoolIds) {
712         entitlementPoolDao.removeReferencingFeatureGroup(
713             new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(),
714                 featureGroup.getVersion(), entitlementPoolId), featureGroup.getId());
715       }
716     }
717   }
718
719   protected void updateUniqueName(String uniqueValueType, String oldName, String newName, String...
720       context) {
721     UniqueValueUtil
722         .updateUniqueValue(uniqueValueType, oldName, newName, context);
723   }
724
725   protected void deleteUniqueName(String uniqueValueType, String... uniqueCombination) {
726     UniqueValueUtil.deleteUniqueValue(uniqueValueType, uniqueCombination);
727   }
728 }