Fixed SONAR issues
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / test / java / org / openecomp / sdc / vendorsoftwareproduct / impl / VendorSoftwareProductManagerImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.vendorsoftwareproduct.impl;
22
23 import org.mockito.ArgumentCaptor;
24 import org.mockito.Captor;
25 import org.mockito.InjectMocks;
26 import org.mockito.Mock;
27 import org.mockito.MockitoAnnotations;
28 import org.mockito.Spy;
29 import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory;
30 import org.openecomp.core.factory.impl.AbstractFactoryBase;
31 import org.openecomp.core.model.dao.EnrichedServiceModelDao;
32 import org.openecomp.core.model.dao.ServiceModelDao;
33 import org.openecomp.core.model.types.ServiceElement;
34 import org.openecomp.core.utilities.file.FileContentHandler;
35 import org.openecomp.core.utilities.file.FileUtils;
36 import org.openecomp.sdc.activityLog.ActivityLogManager;
37 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
38 import org.openecomp.sdc.common.errors.CoreException;
39 import org.openecomp.sdc.common.errors.ErrorCategory;
40 import org.openecomp.sdc.common.errors.ErrorCode;
41 import org.openecomp.sdc.common.errors.Messages;
42 import org.openecomp.sdc.healing.api.HealingManager;
43 import org.openecomp.sdc.logging.api.Logger;
44 import org.openecomp.sdc.logging.api.LoggerFactory;
45 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
46 import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition;
47 import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
48 import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService;
49 import org.openecomp.sdc.vendorsoftwareproduct.ManualVspToscaManager;
50 import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager;
51 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
52 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
53 import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao;
54 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
55 import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao;
56 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
57 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
58 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity;
59 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
60 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity;
61 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
62 import org.openecomp.sdc.vendorsoftwareproduct.impl.mock.EnrichmentManagerFactoryImpl;
63 import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator;
64 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
65 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
66 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
67 import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo;
68 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor;
69 import org.openecomp.sdc.versioning.VersioningManager;
70 import org.openecomp.sdc.versioning.dao.types.Version;
71 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
72 import org.openecomp.sdc.versioning.errors.EditOnEntityLockedByOtherErrorBuilder;
73 import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder;
74 import org.openecomp.sdc.versioning.types.VersionInfo;
75 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
76 import org.testng.Assert;
77 import org.testng.annotations.BeforeMethod;
78 import org.testng.annotations.Test;
79
80 import java.io.File;
81 import java.io.FileInputStream;
82 import java.io.IOException;
83 import java.io.InputStream;
84 import java.net.URL;
85 import java.nio.ByteBuffer;
86 import java.util.ArrayList;
87 import java.util.Arrays;
88 import java.util.Collections;
89 import java.util.HashMap;
90 import java.util.List;
91 import java.util.Map;
92 import java.util.zip.ZipEntry;
93 import java.util.zip.ZipInputStream;
94
95 import static org.mockito.Matchers.any;
96 import static org.mockito.Matchers.anyObject;
97 import static org.mockito.Matchers.eq;
98 import static org.mockito.Mockito.doNothing;
99 import static org.mockito.Mockito.doReturn;
100 import static org.mockito.Mockito.doThrow;
101 import static org.mockito.Mockito.never;
102 import static org.mockito.Mockito.verify;
103
104
105 public class VendorSoftwareProductManagerImplTest {
106
107   private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName());
108
109   private static final String INVALID_VERSION_MSG = "Invalid requested version.";
110
111   private static String VSP_ID = "vspId";
112   private static String VERSION_ID = "versionId";
113   public static final Version VERSION01 = new Version(0, 1);
114   private static final Version VERSION10 = new Version(1, 0);
115   private static final String USER1 = "vspTestUser1";
116   private static final String USER2 = "vspTestUser2";
117   private static final String USER3 = "vspTestUser3";
118   private static String id006 = null;
119   private static String id007 = null;
120
121   @Mock
122   private VersioningManager versioningManagerMock;
123   @Mock
124   private VendorSoftwareProductDao vendorSoftwareProductDaoMock; // todo get rid of
125   @Mock
126   private OrchestrationTemplateDao orchestrationTemplateDataDaoMock;
127   @Mock
128   private VendorLicenseFacade vendorLicenseFacadeMock;
129   @Mock
130   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDaoMock;
131   @Mock
132   private EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDaoMock;
133   @Mock
134   private HealingManager healingManagerMock;
135   @Mock
136   private VendorLicenseArtifactsService licenseArtifactsServiceMock;
137   @Mock
138   private CompositionEntityDataManager compositionEntityDataManagerMock;
139   @Mock
140   private InformationArtifactGenerator informationArtifactGeneratorMock;
141   @Mock
142   private ActivityLogManager activityLogManagerMock;
143   @Mock
144   private PackageInfoDao packageInfoDao;
145   @Mock
146   private VendorSoftwareProductInfoDao vspInfoDaoMock;
147   @Mock
148   private ManualVspToscaManager manualVspToscaManager;
149   @Mock
150   private DeploymentFlavorDao deploymentFlavorDaoMock;
151
152
153   @Spy
154   @InjectMocks
155   private VendorSoftwareProductManagerImpl vendorSoftwareProductManager;
156
157   private OrchestrationTemplateCandidateManager candidateManager;
158   private MonitoringUploadsManager monitoringUploadsManager;
159
160   @Captor
161   private ArgumentCaptor<ActivityLogEntity> activityLogEntityArg;
162
163   @BeforeMethod
164   public void setUp() throws Exception {
165     MockitoAnnotations.initMocks(this);
166   }
167
168   @Test
169   public void testListWhenNone() {
170     doReturn(new HashMap<>()).when(versioningManagerMock).listEntitiesVersionInfo
171             (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1,
172                     VersionableEntityAction.Read);
173     List<VersionedVendorSoftwareProductInfo> vsps =
174             vendorSoftwareProductManager.listVsps(null, USER1);
175     Assert.assertEquals(vsps.size(), 0);
176   }
177
178   @Test
179   public void testList() {
180     String vsp1id = "vsp1_id";
181     String vsp2id = "vsp2_id";
182     Map<String, VersionInfo> vspsTobeReturned = new HashMap<>();
183
184     VersionInfo versionInfo1 = new VersionInfo();
185     versionInfo1.setActiveVersion(VERSION01);
186     vspsTobeReturned.put(vsp1id, versionInfo1);
187
188     VersionInfo versionInfo2 = new VersionInfo();
189     versionInfo2.setActiveVersion(VERSION10);
190     vspsTobeReturned.put(vsp2id, versionInfo2);
191
192     doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo
193             (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1,
194                     VersionableEntityAction.Read);
195
196     VspDetails vsp1 = new VspDetails(vsp1id, VERSION01);
197     vsp1.setWritetimeMicroSeconds(8L);
198     doReturn(vsp1).when(vspInfoDaoMock)
199             .get(any(VspDetails.class));
200
201     List<VersionedVendorSoftwareProductInfo> vsps =
202             vendorSoftwareProductManager.listVsps(null, USER1);
203     Assert.assertEquals(vsps.size(), 2);
204   }
205
206   @Test
207   public void testListFinalsWhenNone() {
208     String vsp1id = "vsp1_id";
209     String vsp2id = "vsp2_id";
210     Map<String, VersionInfo> vspsTobeReturned = new HashMap<>();
211
212     VersionInfo versionInfo1 = new VersionInfo();
213     versionInfo1.setActiveVersion(VERSION01);
214     vspsTobeReturned.put(vsp1id, versionInfo1);
215
216     VersionInfo versionInfo2 = new VersionInfo();
217     versionInfo2.setActiveVersion(VERSION10);
218     vspsTobeReturned.put(vsp2id, versionInfo2);
219
220     doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo
221             (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1,
222                     VersionableEntityAction.Read);
223
224     List<VersionedVendorSoftwareProductInfo> vsps =
225             vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), USER1);
226     Assert.assertEquals(vsps.size(), 0);
227   }
228
229   @Test
230   public void testListFinals() {
231     String vsp1id = "vsp1_id";
232     String vsp2id = "vsp2_id";
233     Map<String, VersionInfo> vspsTobeReturned = new HashMap<>();
234
235     VersionInfo versionInfo1 = new VersionInfo();
236     versionInfo1.setActiveVersion(VERSION01);
237     vspsTobeReturned.put(vsp1id, versionInfo1);
238
239     VersionInfo versionInfo2 = new VersionInfo();
240     versionInfo2.setActiveVersion(new Version(1, 3));
241     versionInfo2.setLatestFinalVersion(VERSION10);
242     vspsTobeReturned.put(vsp2id, versionInfo2);
243
244     doReturn(vspsTobeReturned).when(versioningManagerMock).listEntitiesVersionInfo
245             (VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, USER1,
246                     VersionableEntityAction.Read);
247
248     VspDetails vsp2 = new VspDetails(vsp2id, VERSION10);
249     vsp2.setWritetimeMicroSeconds(8L);
250     doReturn(vsp2).when(vspInfoDaoMock)
251             .get(any(VspDetails.class));
252
253     List<VersionedVendorSoftwareProductInfo> vsps =
254             vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), USER1);
255     Assert.assertEquals(vsps.size(), 1);
256   }
257
258   @Test(expectedExceptions = CoreException.class)
259   public void testCreateWithExistingName_negative() {
260     doThrow(new CoreException(
261             new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build()))
262             .when(vendorSoftwareProductManager).validateUniqueName("Vsp1");
263     VspDetails expectedVsp =
264             createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
265                     "category", "subCategory", "123", null);
266
267     vendorSoftwareProductManager.createVsp(expectedVsp, USER1);
268   }
269
270   @Test
271   public void testCreate() {
272     doNothing().when(vendorSoftwareProductManager).validateUniqueName("Vsp1");
273     doNothing().when(vendorSoftwareProductManager).createUniqueName("Vsp1");
274     doReturn(VERSION01).when(versioningManagerMock).create(anyObject(), anyObject(), anyObject());
275     doReturn("{}")
276             .when(vendorSoftwareProductManager).getVspQuestionnaireSchema(anyObject());
277
278     VspDetails vspToCreate =
279             createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
280                     "category", "subCategory", "123", null);
281
282     VspDetails vsp = vendorSoftwareProductManager.createVsp(vspToCreate, USER1);
283
284     Assert.assertNotNull(vsp);
285     vspToCreate.setId(vsp.getId());
286     vspToCreate.setVersion(VERSION01);
287     assertVspsEquals(vsp, vspToCreate);
288     verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1));
289     ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue();
290     Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1));
291     Assert.assertTrue(activityLogEntity.isSuccess());
292   }
293
294   @Test(expectedExceptions = CoreException.class)
295   public void testUpdateWithExistingName_negative() {
296     VersionInfo versionInfo = new VersionInfo();
297     versionInfo.setActiveVersion(VERSION01);
298     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
299             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
300             VersionableEntityAction.Write);
301
302     VspDetails existingVsp =
303             createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-existingVsp", "vendorName", "vlm1Id",
304                     "icon", "category", "subCategory", "123", null);
305     VspDetails updatedVsp =
306             createVspDetails(VSP_ID, VERSION01, "Vsp1_updated", "Test-existingVsp", "vendorName",
307                     "vlm1Id", "icon", "category", "subCategory", "123", null);
308     doReturn(existingVsp).when(vspInfoDaoMock)
309             .get(any(VspDetails.class));
310     doThrow(new CoreException(
311             new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build()))
312             .when(vendorSoftwareProductManager)
313             .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
314
315     vendorSoftwareProductManager.updateVsp(updatedVsp, USER1);
316   }
317
318   @Test
319   public void testUpdate() {
320     VersionInfo versionInfo = new VersionInfo();
321     versionInfo.setActiveVersion(VERSION01);
322     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
323             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
324             VersionableEntityAction.Write);
325     VspDetails existingVsp =
326             createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
327                     "category",
328                     "subCategory", "456", null);
329     VspDetails updatedVsp =
330             createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon",
331                     "category_updated",
332                     "subCategory", "456", null);
333     existingVsp.setWritetimeMicroSeconds(8L);
334     doReturn(existingVsp).when(vspInfoDaoMock)
335             .get(any(VspDetails.class));
336     doNothing().when(vendorSoftwareProductManager)
337             .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
338
339     vendorSoftwareProductManager.updateVsp(updatedVsp, USER1);
340
341     verify(vspInfoDaoMock).update(updatedVsp);
342   }
343
344   @Test
345   public void testUpdateRemoveFG() {
346     VersionInfo versionInfo = new VersionInfo();
347     versionInfo.setActiveVersion(VERSION01);
348     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
349             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
350             VersionableEntityAction.Write);
351     List<String> fgs = new ArrayList<String>();
352     fgs.add("fg1"); fgs.add("fg2");
353     VspDetails existingVsp =
354             createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
355                     "category",
356                     "subCategory", "456", fgs);
357
358     List<String> updFgs = new ArrayList<String>();
359     updFgs.add("fg2");
360     VspDetails updatedVsp =
361             createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon",
362                     "category_updated",
363                     "subCategory", "456", updFgs);
364     existingVsp.setWritetimeMicroSeconds(8L);
365     doReturn(existingVsp).when(vspInfoDaoMock)
366             .get(any(VspDetails.class));
367     doNothing().when(vendorSoftwareProductManager)
368             .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
369
370     DeploymentFlavorEntity dfEntity = new DeploymentFlavorEntity(VSP_ID,VERSION01,"DF_ID");
371     DeploymentFlavor flavor = new DeploymentFlavor();
372     flavor.setFeatureGroupId("fg1");
373     dfEntity.setDeploymentFlavorCompositionData(flavor);
374
375     List<DeploymentFlavorEntity> dfList = new ArrayList<DeploymentFlavorEntity>();
376     dfList.add(dfEntity);
377
378     doReturn(dfList).when(deploymentFlavorDaoMock).list(anyObject());
379
380     vendorSoftwareProductManager.updateVsp(updatedVsp, USER1);
381
382     verify(vendorSoftwareProductDaoMock).updateDeploymentFlavor(dfEntity);
383
384     Assert.assertNull(dfEntity.getDeploymentFlavorCompositionData().getFeatureGroupId());
385
386   }
387
388   @Test(expectedExceptions = CoreException.class)
389   public void testGetNonExistingVersion_negative() {
390     Version notExistversion = new Version(43, 8);
391     doReturn(null).when(vspInfoDaoMock).get(any(VspDetails.class));
392     vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion, USER1);
393   }
394
395   @Test
396   public void testGetCheckedOutVersion() {
397     VersionInfo versionInfo = new VersionInfo();
398     versionInfo.setActiveVersion(VERSION01);
399     versionInfo.setStatus(VersionStatus.Locked);
400     versionInfo.setLockingUser(USER1);
401     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
402             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
403             VersionableEntityAction.Read);
404
405     VspDetails existingVsp =
406             createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
407                     "category",
408                     "subCategory", "456", null);
409     existingVsp.setWritetimeMicroSeconds(8L);
410     doReturn(existingVsp).when(vspInfoDaoMock).get(any(VspDetails.class));
411
412     VspDetails actualVsp =
413             vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01, USER1);
414
415     assertVspsEquals(actualVsp, existingVsp);
416   }
417
418   @Test
419   public void testGetOldVersion() {
420     VersionInfo versionInfo = new VersionInfo();
421     versionInfo.setActiveVersion(new Version(0, 2));
422     versionInfo.setViewableVersions(Arrays.asList(VERSION01, new Version(0, 2)));
423     versionInfo.setStatus(VersionStatus.Locked);
424     versionInfo.setLockingUser(USER2);
425     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
426             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
427             VersionableEntityAction.Read);
428
429     VspDetails existingVsp =
430             createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
431                     "category",
432                     "subCategory", "456", null);
433     existingVsp.setWritetimeMicroSeconds(8L);
434     doReturn(existingVsp)
435             .when(vspInfoDaoMock).get(any(VspDetails.class));
436
437     VspDetails actualVsp =
438             vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01, USER1);
439
440     VspDetails expectedVsp =
441             vspInfoDaoMock
442                     .get(new VspDetails(VSP_ID, VERSION01));
443     assertVspsEquals(actualVsp, expectedVsp);
444   }
445
446   @Test
447   public void testCheckin() {
448     doReturn(VERSION01).when(versioningManagerMock)
449             .checkin(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
450                     USER1, null);
451     Version version = vendorSoftwareProductManager.checkin(VSP_ID, USER1);
452
453     Assert.assertEquals(version, VERSION01);
454     verify(versioningManagerMock)
455             .checkin(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
456                     USER1, null);
457     verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1));
458     ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue();
459     Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1));
460     Assert.assertTrue(activityLogEntity.isSuccess());
461   }
462
463   @Test
464   public void testCheckout() {
465     doReturn(VERSION01).when(versioningManagerMock)
466             .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
467                     USER1);
468     Version version = vendorSoftwareProductManager.checkout(VSP_ID, USER1);
469
470     Assert.assertEquals(version, VERSION01);
471     verify(versioningManagerMock)
472             .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
473                     USER1);
474
475     verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1));
476     ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue();
477     Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION01.getMajor() + 1));
478     Assert.assertTrue(activityLogEntity.isSuccess());
479   }
480
481
482   @Test
483   public void testUndoCheckout() {
484     Version existingVersion = new Version(0, 2);
485     VersionInfo versionInfo = new VersionInfo();
486     versionInfo.setActiveVersion(existingVersion);
487     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
488             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
489             VSP_ID, USER1, VersionableEntityAction.Read);
490
491     doReturn(VERSION01).when(versioningManagerMock).undoCheckout(VendorSoftwareProductConstants
492             .VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1);
493
494     VspDetails vsp = new VspDetails(VSP_ID, existingVersion);
495     vsp.setName("ExistingName");
496     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
497     doNothing().when(vendorSoftwareProductManager).updateUniqueName(vsp.getName(), vsp.getName());
498
499     Version undoCheckoutVersion = vendorSoftwareProductManager.undoCheckout(VSP_ID, USER1);
500
501     Assert.assertEquals(undoCheckoutVersion, VERSION01);
502   }
503
504 /*
505   @Test
506   public void testSubmitWithMissingData() throws IOException {
507     VersionInfo versionInfo = new VersionInfo();
508     versionInfo.setActiveVersion(VERSION01);
509
510     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
511         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
512         VSP_ID, USER1, VersionableEntityAction.Read);
513
514     VspDetails vsp = new VspDetails(VSP_ID, VERSION01);
515     vsp.setOnboardingMethod("Manual");
516     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
517
518     VspQuestionnaireEntity vspQuestionnaire = new VspQuestionnaireEntity(VSP_ID, VERSION01);
519     vspQuestionnaire.setQuestionnaireData("{}");
520     doReturn(vspQuestionnaire).when(vspInfoDaoMock).getQuestionnaire(VSP_ID, VERSION01);
521
522     ComponentEntity comp1 = new ComponentEntity(VSP_ID, VERSION01, "comp1");
523     comp1.setQuestionnaireData("{}");
524     doReturn(Collections.singleton(comp1)).when(vendorSoftwareProductDaoMock)
525         .listComponentsCompositionAndQuestionnaire(VSP_ID, VERSION01);
526
527     NicEntity nic1 = new NicEntity(VSP_ID, VERSION01, "comp1", "nic1");
528     nic1.setQuestionnaireData("{}");
529     doReturn(Collections.singleton(nic1))
530         .when(vendorSoftwareProductDaoMock).listNicsByVsp(VSP_ID, VERSION01);
531
532     ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1);
533     Assert.assertNotNull(validationResponse);
534     Assert.assertFalse(validationResponse.isValid());
535     List<String> errorIds = validationResponse.getVspErrors().stream().map(ErrorCode::id).distinct()
536         .collect(Collectors.toList());
537     Assert.assertTrue(errorIds.contains(ValidationErrorBuilder.FIELD_VALIDATION_ERROR_ERR_ID));
538     Assert.assertTrue(errorIds.contains(VendorSoftwareProductErrorCodes.VSP_INVALID));
539
540     verify(versioningManagerMock, never())
541         .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
542             USER1, null);
543     verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1));
544   }
545
546   */
547
548   // TODO: 3/15/2017 fix and enable
549   //@Test
550   public void testSubmitWithInvalidLicensingData() throws IOException {
551     VersionInfo versionInfo = new VersionInfo();
552     versionInfo.setActiveVersion(VERSION01);
553     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
554             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
555             VSP_ID, USER1, VersionableEntityAction.Read);
556
557     VspDetails vsp =
558             createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
559                     "category", "subCategory", "licenseAgreementId",
560                     Collections.singletonList("featureGroupId"));
561     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
562     UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01);
563     uploadData.setContentData(
564             ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition"))));
565     doReturn(uploadData).when(orchestrationTemplateDataDaoMock)
566             .getOrchestrationTemplate(anyObject(), anyObject());
567     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(),
568             "MainServiceTemplate.yaml"))
569             .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01);
570
571     ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1);
572     Assert.assertNotNull(validationResponse);
573     Assert.assertFalse(validationResponse.isValid());
574     Assert.assertNull(validationResponse.getVspErrors());
575     Assert.assertEquals(validationResponse.getLicensingDataErrors(), 1);
576
577     verify(versioningManagerMock, never())
578             .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
579                     USER1, null);
580
581     //TODO - check..
582     verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1));
583   }
584
585   // TODO: 3/15/2017 fix and enable
586   //@Test
587   public void testSubmit() throws IOException {
588     mockVersioning(VersionableEntityAction.Read);
589
590     EnrichmentManagerFactory.getInstance();
591     AbstractFactoryBase
592             .registerFactory(EnrichmentManagerFactory.class, EnrichmentManagerFactoryImpl.class);
593
594     VspDetails vsp =
595             createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
596                     "category", "subCategory", "123", Collections.singletonList("fg1"));
597     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
598     UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01);
599     uploadData.setContentData(
600             ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition"))));
601     doReturn(uploadData).when(orchestrationTemplateDataDaoMock)
602             .getOrchestrationTemplate(anyObject(), anyObject());
603     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(),
604             "MainServiceTemplate.yaml"))
605             .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01);
606
607     ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1);
608     Assert.assertTrue(validationResponse.isValid());
609
610 /*    Assert.assertEquals(vsp2.getVersionInfo().getActiveVersion(), VERSION10);
611     Assert.assertEquals(vsp2.getVersionInfo().getStatus(), VersionStatus.Final);
612     Assert.assertNull(vsp2.getVersionInfo().getLockingUser());*/
613
614     verify(versioningManagerMock)
615             .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
616                     USER1, null);
617     verify(activityLogManagerMock).addActionLog(activityLogEntityArg.capture(), eq(USER1));
618     ActivityLogEntity activityLogEntity = activityLogEntityArg.getValue();
619     Assert.assertEquals(activityLogEntity.getVersionId(), String.valueOf(VERSION10.getMajor()));
620     Assert.assertTrue(activityLogEntity.isSuccess());
621   }
622
623   @Test(expectedExceptions = CoreException.class)
624   public void testCreatePackageOnNonFinalVersion_negative() throws IOException {
625     vendorSoftwareProductManager.createPackage(VSP_ID, VERSION01, USER1);
626   }
627
628   @Test
629   public void testCreatePackage() throws IOException {
630     /*VspDetails vspDetailsMock = new VspDetails("vspId", new Version(1, 0));
631     doReturn(vspDetailsMock).when(vspInfoDaoMock).get(anyObject());*/
632     VersionInfo versionInfo = new VersionInfo();
633     versionInfo.setActiveVersion(VERSION10);
634     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
635             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
636             VersionableEntityAction.Read);
637
638     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), "")).when
639             (enrichedServiceModelDaoMock).getServiceModel(VSP_ID, VERSION10);
640
641     VspDetails vsp = new VspDetails(VSP_ID, VERSION10);
642     vsp.setVendorId("vendorId");
643     vsp.setVlmVersion(VERSION10);
644     vsp.setFeatureGroups(Arrays.asList("fg1", "fg2"));
645     doReturn(vsp).when(vspInfoDaoMock).get(any(VspDetails.class));
646
647     doReturn(new FileContentHandler()).when(licenseArtifactsServiceMock)
648             .createLicenseArtifacts(VSP_ID, vsp.getVendorId(), VERSION10, vsp.getFeatureGroups(),
649                     USER1);
650
651     PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(VSP_ID, VERSION10, USER1);
652     Assert.assertNotNull(packageInfo.getVspId());
653   }
654
655   // TODO: 3/15/2017 fix and enable
656   //@Test(dependsOnMethods = {"testListFinals"})
657   public void testUploadFileMissingFile() {
658     InputStream zis = getFileInputStream("/vspmanager/zips/missingYml.zip");
659
660     UploadFileResponse uploadFileResponse =
661             candidateManager.upload(VSP_ID, VERSION01, zis, USER1, "zip", "missingYml");
662
663     Assert.assertEquals(uploadFileResponse.getErrors().size(), 0);
664   }
665
666   // TODO: 3/15/2017 fix and enable
667   //@Test(dependsOnMethods = {"testUploadFileMissingFile"})
668   public void testUploadNotZipFile() throws IOException {
669     URL url = this.getClass().getResource("/notZipFile");
670
671     try {
672       candidateManager
673               .upload(VSP_ID, VERSION01,
674                       url.openStream(), USER1, "zip", "notZipFile");
675       candidateManager.process(VSP_ID, VERSION01, USER1);
676     } catch (Exception ce) {
677       log.debug("",ce);
678       Assert.assertEquals(ce.getMessage(), Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage());
679     }
680
681     verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1));
682   }
683
684
685   private List<String> getWantedFileNamesFromCsar(String pathInCsar)
686           throws IOException {
687     File translatedFile = vendorSoftwareProductManager.getTranslatedFile(VSP_ID, VERSION10, USER1);
688
689     return getFileNamesFromFolderInCsar(translatedFile,
690             pathInCsar);
691   }
692
693   private List<String> getFileNamesFromFolderInCsar(File csar, String folderName)
694           throws IOException {
695     List<String> fileNames = new ArrayList<>();
696
697     FileInputStream fileInputStream = new FileInputStream(csar);
698     try {
699       ZipInputStream zip = new ZipInputStream(fileInputStream);
700       ZipEntry ze;
701
702       while ((ze = zip.getNextEntry()) != null) {
703         String name = ze.getName();
704         if (name.contains(folderName)) {
705           fileNames.add(name);
706         }
707       }
708     }finally {
709       fileInputStream.close();
710     }
711
712     return fileNames;
713   }
714
715   private void createPackageFromUpload(String vspId, String user, String filePath)
716           throws IOException {
717     uploadFileAndProcess(vspId, user, filePath);
718     checkinSubmitCreatePackage(vspId, user);
719   }
720
721   private void uploadFileAndProcess(String vspId, String user, String filePath) {
722     vendorSoftwareProductManager.checkout(vspId, user);
723     candidateManager.upload(vspId, VERSION01, getFileInputStream(filePath), user, "zip", "file");
724     candidateManager.process(vspId, VERSION01, user);
725   }
726
727   private void checkinSubmitCreatePackage(String vspId, String user) throws IOException {
728     vendorSoftwareProductManager.checkin(vspId, user);
729     ValidationResponse submitResponse = vendorSoftwareProductManager.submit(vspId, user);
730     Assert.assertTrue(submitResponse.isValid());
731     vendorSoftwareProductManager.createPackage(vspId, VERSION10, user);
732   }
733
734   // TODO: 3/15/2017 fix and enable
735 /*
736
737   public void testUpdatedVSPShouldBeInBeginningOfList() {
738     vendorSoftwareProductManager.updateVsp(new VspDetails(), USER3);
739     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
740
741     InputStream zis = getFileInputStream("/vspmanager/zips/fullComposition.zip");
742     candidateManager.upload(id007, VERSION01, zis, USER3);
743     candidateManager.process(id007, VERSION01, USER3);
744     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
745   }
746
747   @Test(dependsOnMethods = {"testUpdatedVSPShouldBeInBeginningOfList"})
748   public void testVSPInBeginningOfListAfterCheckin() {
749     vendorSoftwareProductManager.checkin(id006, USER3);
750     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
751
752     vendorSoftwareProductManager.checkin(id007, USER3);
753     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
754   }
755
756   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterCheckin"})
757   public void testVSPInBeginningOfListAfterCheckout() {
758     vendorSoftwareProductManager.checkout(id006, USER3);
759     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
760   }
761
762   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterCheckout"})
763   public void testVSPInBeginningOfListAfterUndoCheckout() {
764     vendorSoftwareProductManager.checkout(id007, USER3);
765     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
766
767     vendorSoftwareProductManager.undoCheckout(id006, USER3);
768     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
769   }
770
771   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterUndoCheckout"})
772   public void testVSPInBeginningOfListAfterSubmit() throws IOException {
773     vendorSoftwareProductManager.checkin(id007, USER3);
774     vendorSoftwareProductManager.submit(id007, USER3);
775
776     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
777   }
778 */
779
780   private void testLegalUpload(String vspId, Version version, InputStream upload, String user) {
781     candidateManager.upload(vspId, VERSION01, upload, USER1, "zip", "file");
782     candidateManager.process(vspId, VERSION01, user);
783
784     UploadDataEntity uploadData =
785             orchestrationTemplateDataDaoMock.getOrchestrationTemplate(vspId, version);
786     Assert.assertNotNull(uploadData);
787   }
788
789   private void addCapability(String entryValueKey, Map<String, CapabilityDefinition> capabilities,
790                              String key, CapabilityDefinition value) {
791
792     capabilities.put(entryValueKey + "_" + key, value);
793   }
794
795   public InputStream getFileInputStream(String fileName) {
796     URL url = this.getClass().getResource(fileName);
797     try {
798       return url.openStream();
799     } catch (IOException exception) {
800       exception.printStackTrace();
801       return null;
802     }
803   }
804
805   private void assertVSPInWantedLocationInVSPList(String vspId, int location, String user) {
806     List<VersionedVendorSoftwareProductInfo> vspList =
807             vendorSoftwareProductManager.listVsps(null, user);
808     Assert.assertEquals(vspList.get(location).getVspDetails().getId(), vspId);
809   }
810
811
812   static VspDetails createVspDetails(String id, Version version, String name, String desc,
813                                      String vendorName, String vlm, String icon,
814                                      String category, String subCategory,
815                                      String licenseAgreement, List<String> featureGroups) {
816     VspDetails vspDetails = new VspDetails(id, version);
817     vspDetails.setName(name);
818     vspDetails.setDescription(desc);
819     vspDetails.setIcon(icon);
820     vspDetails.setCategory(category);
821     vspDetails.setSubCategory(subCategory);
822     vspDetails.setVendorName(vendorName);
823     vspDetails.setVendorId(vlm);
824     vspDetails.setVlmVersion(new Version(1, 0));
825     vspDetails.setLicenseAgreement(licenseAgreement);
826     vspDetails.setFeatureGroups(featureGroups);
827     vspDetails.setOnboardingMethod("HEAT");
828     return vspDetails;
829   }
830
831   static void assertVspsEquals(VspDetails actual, VspDetails expected) {
832     Assert.assertEquals(actual.getId(), expected.getId());
833     Assert.assertEquals(actual.getVersion(), expected.getVersion());
834     Assert.assertEquals(actual.getName(), expected.getName());
835     Assert.assertEquals(actual.getDescription(), expected.getDescription());
836     Assert.assertEquals(actual.getIcon(), expected.getIcon());
837     Assert.assertEquals(actual.getCategory(), expected.getCategory());
838     Assert.assertEquals(actual.getSubCategory(), expected.getSubCategory());
839     Assert.assertEquals(actual.getVendorName(), expected.getVendorName());
840     Assert.assertEquals(actual.getVendorId(), expected.getVendorId());
841     Assert.assertEquals(actual.getLicenseAgreement(), expected.getLicenseAgreement());
842     Assert.assertEquals(actual.getFeatureGroups(), expected.getFeatureGroups());
843   }
844
845  // todo ********************** move to common **************************************
846
847   private void mockVersioning(VersionableEntityAction action) {
848     VersionInfo versionInfo = new VersionInfo();
849     versionInfo.setActiveVersion(VERSION01);
850     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
851             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
852             action);
853   }
854
855   private void mockVersioningEntityNotExist(VersionableEntityAction action, String vspId) {
856     doThrow(new CoreException(new EntityNotExistErrorBuilder(
857             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId).build()))
858             .when(versioningManagerMock).getEntityVersionInfo(
859             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, vspId, USER1,
860             action);
861   }
862
863   private void MockVersioningEntityLocked(VersionableEntityAction action) {
864     doThrow(new CoreException(new EditOnEntityLockedByOtherErrorBuilder(
865             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1)
866             .build()))
867             .when(versioningManagerMock).getEntityVersionInfo(
868             VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER2,
869             action);
870   }
871 }