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