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