Added oparent to sdc main
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / test / java / org / openecomp / sdc / vendorsoftwareproduct / impl / VendorSoftwareProductManagerImplTest.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.vendorsoftwareproduct.impl;
18
19 import org.apache.commons.io.IOUtils;
20 import org.junit.After;
21 import org.junit.Assert;
22 import org.junit.Before;
23 import org.junit.Test;
24 import org.mockito.ArgumentCaptor;
25 import org.mockito.Captor;
26 import org.mockito.InjectMocks;
27 import org.mockito.Mock;
28 import org.mockito.MockitoAnnotations;
29 import org.mockito.Spy;
30 import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory;
31 import org.openecomp.core.factory.impl.AbstractFactoryBase;
32 import org.openecomp.core.model.dao.EnrichedServiceModelDao;
33 import org.openecomp.core.model.dao.ServiceModelDao;
34 import org.openecomp.core.model.types.ServiceElement;
35 import org.openecomp.core.utilities.file.FileContentHandler;
36 import org.openecomp.core.utilities.file.FileUtils;
37 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
38 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
39 import org.openecomp.sdc.common.errors.CoreException;
40 import org.openecomp.sdc.common.errors.ErrorCategory;
41 import org.openecomp.sdc.common.errors.ErrorCode;
42 import org.openecomp.sdc.common.errors.Messages;
43 import org.openecomp.sdc.healing.api.HealingManager;
44 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
45 import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
46 import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService;
47 import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManager;
48 import org.openecomp.sdc.vendorsoftwareproduct.ManualVspToscaManager;
49 import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager;
50 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
51 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
52 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao;
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.VendorSoftwareProductInfoDao;
57 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity;
58 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
59 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
60 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
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.types.UploadFileResponse;
65 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
66 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor;
67 import org.openecomp.sdc.versioning.ActionVersioningManager;
68 import org.openecomp.sdc.versioning.dao.types.Version;
69 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
70 import org.openecomp.sdc.versioning.types.VersionInfo;
71 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
72
73 import java.io.File;
74 import java.io.FileInputStream;
75 import java.io.IOException;
76 import java.io.InputStream;
77 import java.net.URL;
78 import java.nio.ByteBuffer;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.Collections;
82 import java.util.HashMap;
83 import java.util.List;
84 import java.util.Optional;
85 import java.util.zip.ZipEntry;
86 import java.util.zip.ZipInputStream;
87
88 import static org.junit.Assert.assertEquals;
89 import static org.junit.Assert.assertTrue;
90 import static org.junit.Assert.fail;
91 import static org.mockito.ArgumentMatchers.any;
92 import static org.mockito.ArgumentMatchers.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 import static org.mockito.Mockito.when;
99 import static org.openecomp.sdc.tosca.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_MF_FILE_NAME;
100 import static org.openecomp.sdc.tosca.csar.CSARConstants.TOSCA_META_PATH_FILE_NAME;
101
102
103
104 public class VendorSoftwareProductManagerImplTest {
105
106   private static final String VSP_ID = "vspId";
107   private static final Version VERSION01 = new Version("0, 1");
108   private static final Version VERSION10 = new Version("1, 0");
109   private static final String USER1 = "vspTestUser1";
110   private static final String USER2 = "vspTestUser2";
111
112   @Mock
113   private ActionVersioningManager 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   @Mock
145   private OrchestrationTemplateCandidateManager orchestrationTemplateCandidateManagerMock;
146   @Mock
147   private ComponentDependencyModelDao componentDependencyModelDao;
148   private OrchestrationTemplateCandidateManager candidateManager;
149   private MonitoringUploadsManager monitoringUploadsManager;
150
151   @Captor
152   private ArgumentCaptor<ActivityLogEntity> activityLogEntityArg;
153
154   @Before
155   public void setUp() {
156     MockitoAnnotations.initMocks(this);
157   }
158
159   @After
160   public void tearDown() {
161     vendorSoftwareProductManager = null;
162   }
163
164   @Test
165   public void testCreatePackageEtsiVNF(){
166     try(InputStream metadataInput = getClass().getResourceAsStream("/vspmanager.csar/metadata/ValidETSItosca.meta");
167         InputStream manifestInput = getClass().getResourceAsStream("/vspmanager.csar/manifest/ValidNonManoTosca.mf")) {
168
169       FileContentHandler handler = new FileContentHandler();
170       handler.addFile(TOSCA_META_PATH_FILE_NAME, IOUtils.toByteArray(metadataInput));
171       handler.addFile(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME, IOUtils.toByteArray(manifestInput));
172       ToscaServiceModel toscaMetadata = new ToscaServiceModel(handler, new HashMap<>(), "");
173       when(enrichedServiceModelDaoMock.getServiceModel(any(), any())).thenReturn(toscaMetadata );
174       VspDetails vsp =
175               createVspDetails("0", new Version(), "Vsp_PNF", "Test-vsp-pnf", "vendorName", "esy", "icon",
176                       "category", "subCategory", "123", null);
177       //want to avoid triggering populateVersionsForVlm method
178       vsp.setVlmVersion(null);
179
180       when(vspInfoDaoMock.get(any())).thenReturn(vsp);
181       when(licenseArtifactsServiceMock.createLicenseArtifacts(any(),any(), any(), any())).thenReturn(new FileContentHandler());
182       PackageInfo packageInfo = vendorSoftwareProductManager.createPackage("0", new Version());
183       assertEquals(packageInfo.getResourceType(), ResourceTypeEnum.VF.name());
184     } catch (IOException e) {
185       fail();
186     }
187   }
188
189   @Test(expected = IOException.class)
190   public void testCreatePackageEtsiNoManifest() throws IOException {
191     try(InputStream metadataInput = getClass().getResourceAsStream("/vspmanager.csar/metadata/ValidETSItosca.meta"))
192     {
193       FileContentHandler handler = new FileContentHandler();
194       handler.addFile(TOSCA_META_PATH_FILE_NAME, IOUtils.toByteArray(metadataInput));
195       ToscaServiceModel toscaMetadata = new ToscaServiceModel(handler, new HashMap<>(), "");
196       when(enrichedServiceModelDaoMock.getServiceModel(any(), any())).thenReturn(toscaMetadata );
197       VspDetails vsp =
198               createVspDetails("0", new Version(), "Vsp_PNF", "Test-vsp-pnf", "vendorName", "esy", "icon",
199                       "category", "subCategory", "123", null);
200       //want to avoid triggering populateVersionsForVlm method
201       vsp.setVlmVersion(null);
202
203       when(vspInfoDaoMock.get(any())).thenReturn(vsp);
204       when(licenseArtifactsServiceMock.createLicenseArtifacts(any(),any(), any(), any())).thenReturn(new FileContentHandler());
205       vendorSoftwareProductManager.createPackage("0", new Version());
206       fail();
207     }
208   }
209
210   @Test
211   public void testCreatePackageEtsiPNF(){
212     try(InputStream metadataInput = getClass().getResourceAsStream("/vspmanager.csar/metadata/ValidETSItosca.meta");
213         InputStream manifestInput = getClass().getResourceAsStream("/vspmanager.csar/manifest/ValidNonManoToscaPNF.mf")) {
214
215       FileContentHandler handler = new FileContentHandler();
216       handler.addFile(TOSCA_META_PATH_FILE_NAME, IOUtils.toByteArray(metadataInput));
217       handler.addFile(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME, IOUtils.toByteArray(manifestInput));
218       ToscaServiceModel toscaMetadata = new ToscaServiceModel(handler, new HashMap<>(), "");
219       when(enrichedServiceModelDaoMock.getServiceModel(any(), any())).thenReturn(toscaMetadata );
220       VspDetails vsp =
221               createVspDetails("0", new Version(), "Vsp_PNF", "Test-vsp-pnf", "vendorName", "esy", "icon",
222                       "category", "subCategory", "123", null);
223       //want to avoid triggering populateVersionsForVlm method
224       vsp.setVlmVersion(null);
225
226       when(vspInfoDaoMock.get(any())).thenReturn(vsp);
227       when(licenseArtifactsServiceMock.createLicenseArtifacts(any(),any(), any(), any())).thenReturn(new FileContentHandler());
228       PackageInfo packageInfo = vendorSoftwareProductManager.createPackage("0", new Version());
229       assertEquals(packageInfo.getResourceType(), ResourceTypeEnum.PNF.name());
230     } catch (IOException e) {
231       fail();
232     }
233   }
234
235   @Test
236   public void testCreate() {
237     //doReturn(VERSION01).when(versioningManagerMock).create(anyObject(), anyObject(), anyObject());
238     doReturn("{}")
239         .when(vendorSoftwareProductManager).getVspQuestionnaireSchema(anyObject());
240
241     VspDetails vspToCreate =
242         createVspDetails(null, null, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
243             "category", "subCategory", "123", null);
244
245     VspDetails vsp = vendorSoftwareProductManager.createVsp(vspToCreate);
246
247     Assert.assertNotNull(vsp);
248     vspToCreate.setId(vsp.getId());
249     vspToCreate.setVersion(VERSION01);
250     assertVspsEquals(vsp, vspToCreate);
251   }
252
253   @Test(expected = CoreException.class)
254   public void testUpdateWithExistingName_negative() {
255     VersionInfo versionInfo = new VersionInfo();
256     versionInfo.setActiveVersion(VERSION01);
257     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
258         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
259         VersionableEntityAction.Write);
260
261     VspDetails existingVsp =
262         createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-existingVsp", "vendorName", "vlm1Id",
263             "icon", "category", "subCategory", "123", null);
264     VspDetails updatedVsp =
265         createVspDetails(VSP_ID, VERSION01, "Vsp1_updated", "Test-existingVsp", "vendorName",
266             "vlm1Id", "icon", "category", "subCategory", "123", null);
267     doReturn(existingVsp).when(vspInfoDaoMock)
268         .get(any(VspDetails.class));
269     doThrow(new CoreException(
270         new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).build()))
271         .when(vendorSoftwareProductManager)
272         .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
273
274     vendorSoftwareProductManager.updateVsp(updatedVsp);
275   }
276
277   @Test
278   public void testUpdate() {
279     VersionInfo versionInfo = new VersionInfo();
280     versionInfo.setActiveVersion(VERSION01);
281     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
282         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
283         VersionableEntityAction.Write);
284     VspDetails existingVsp =
285         createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
286             "category",
287             "subCategory", "456", null);
288     VspDetails updatedVsp =
289         createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon",
290             "category_updated",
291             "subCategory", "456", null);
292     doReturn(existingVsp).when(vspInfoDaoMock)
293         .get(any(VspDetails.class));
294     doNothing().when(vendorSoftwareProductManager)
295         .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
296
297     vendorSoftwareProductManager.updateVsp(updatedVsp);
298
299     verify(vspInfoDaoMock).update(updatedVsp);
300   }
301
302   @Test
303   public void testUpdateRemoveFG() {
304     VersionInfo versionInfo = new VersionInfo();
305     versionInfo.setActiveVersion(VERSION01);
306     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
307         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
308         VersionableEntityAction.Write);
309     List<String> fgs = new ArrayList<>();
310     fgs.add("fg1");
311     fgs.add("fg2");
312     VspDetails existingVsp =
313         createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
314             "category",
315             "subCategory", "456", fgs);
316
317     List<String> updFgs = new ArrayList<>();
318     //updFgs.add("fg2");
319     VspDetails updatedVsp =
320         createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon",
321             "category_updated",
322             "subCategory", "456", updFgs);
323     doReturn(existingVsp).when(vspInfoDaoMock)
324         .get(any(VspDetails.class));
325     doNothing().when(vendorSoftwareProductManager)
326         .updateUniqueName(existingVsp.getName(), updatedVsp.getName());
327
328     DeploymentFlavorEntity dfEntity = new DeploymentFlavorEntity(VSP_ID, VERSION01, "DF_ID");
329     DeploymentFlavor flavor = new DeploymentFlavor();
330     flavor.setFeatureGroupId("fg1");
331     dfEntity.setDeploymentFlavorCompositionData(flavor);
332
333     List<DeploymentFlavorEntity> dfList = new ArrayList<>();
334     dfList.add(dfEntity);
335
336     doReturn(dfList).when(deploymentFlavorDaoMock).list(anyObject());
337
338     vendorSoftwareProductManager.updateVsp(updatedVsp);
339
340     verify(deploymentFlavorDaoMock).update(dfEntity);
341
342     Assert.assertNull(dfEntity.getDeploymentFlavorCompositionData().getFeatureGroupId());
343
344   }
345
346   @Test(expected = CoreException.class)
347   public void testGetNonExistingVersion_negative() {
348     Version notExistversion = new Version("43, 8");
349     doReturn(null).when(vspInfoDaoMock).get(any(VspDetails.class));
350     vendorSoftwareProductManager.getVsp(VSP_ID, notExistversion);
351   }
352
353   @Test
354   public void testGetCheckedOutVersion() {
355     VersionInfo versionInfo = new VersionInfo();
356     versionInfo.setActiveVersion(VERSION01);
357     versionInfo.setStatus(VersionStatus.Locked);
358     versionInfo.setLockingUser(USER1);
359     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
360         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
361         VersionableEntityAction.Read);
362
363     VspDetails existingVsp =
364         createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
365             "category",
366             "subCategory", "456", null);
367     doReturn(existingVsp).when(vspInfoDaoMock).get(any(VspDetails.class));
368
369     VspDetails actualVsp =
370         vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01);
371
372     assertVspsEquals(actualVsp, existingVsp);
373   }
374
375   @Test
376   public void testGetOldVersion() {
377     VersionInfo versionInfo = new VersionInfo();
378     versionInfo.setActiveVersion(new Version("0, 2"));
379     versionInfo.setViewableVersions(Arrays.asList(VERSION01, new Version("0, 2")));
380     versionInfo.setStatus(VersionStatus.Locked);
381     versionInfo.setLockingUser(USER2);
382     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
383         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
384         VersionableEntityAction.Read);
385
386     VspDetails existingVsp =
387         createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon",
388             "category",
389             "subCategory", "456", null);
390     doReturn(existingVsp)
391         .when(vspInfoDaoMock).get(any(VspDetails.class));
392
393     VspDetails actualVsp =
394         vendorSoftwareProductManager.getVsp(VSP_ID, VERSION01);
395
396     VspDetails expectedVsp =
397         vspInfoDaoMock
398             .get(new VspDetails(VSP_ID, VERSION01));
399     assertVspsEquals(actualVsp, expectedVsp);
400   }
401
402 /*
403   @Test
404   public void testSubmitWithMissingData() throws IOException {
405     VersionInfo versionInfo = new VersionInfo();
406     versionInfo.setActiveVersion(VERSION01);
407
408     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
409         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
410         VSP_ID, USER1, VersionableEntityAction.Read);
411
412     VspDetails vsp = new VspDetails(VSP_ID, VERSION01);
413     vsp.setOnboardingMethod("Manual");
414     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
415
416     VspQuestionnaireEntity vspQuestionnaire = new VspQuestionnaireEntity(VSP_ID, VERSION01);
417     vspQuestionnaire.setQuestionnaireData("{}");
418     doReturn(vspQuestionnaire).when(vspInfoDaoMock).getQuestionnaire(VSP_ID, VERSION01);
419
420     ComponentEntity comp1 = new ComponentEntity(VSP_ID, VERSION01, "comp1");
421     comp1.setQuestionnaireData("{}");
422     doReturn(Collections.singleton(comp1)).when(vendorSoftwareProductDaoMock)
423         .listComponentsCompositionAndQuestionnaire(VSP_ID, VERSION01);
424
425     NicEntity nic1 = new NicEntity(VSP_ID, VERSION01, "comp1", "nic1");
426     nic1.setQuestionnaireData("{}");
427     doReturn(Collections.singleton(nic1))
428         .when(vendorSoftwareProductDaoMock).listNicsByVsp(VSP_ID, VERSION01);
429
430     ValidationResponse validationResponse = vendorSoftwareProductManager.submit(VSP_ID, USER1);
431     Assert.assertNotNull(validationResponse);
432     Assert.assertFalse(validationResponse.isValid());
433     List<String> errorIds = validationResponse.getVspErrors().stream().map(ErrorCode::id).distinct()
434         .collect(Collectors.toList());
435     Assert.assertTrue(errorIds.contains(ValidationErrorBuilder.FIELD_VALIDATION_ERROR_ERR_ID));
436     Assert.assertTrue(errorIds.contains(VendorSoftwareProductErrorCodes.VSP_INVALID));
437
438     verify(versioningManagerMock, never())
439         .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
440             USER1, null);
441     verify(activityLogManagerMock, never()).addActionLog(any(ActivityLogEntity.class), eq(USER1));
442   }
443
444   */
445
446   // TODO: 3/15/2017 fix and enable
447   //@Test
448   public void testSubmitWithInvalidLicensingData() throws IOException {
449     VersionInfo versionInfo = new VersionInfo();
450     versionInfo.setActiveVersion(VERSION01);
451     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
452         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
453         VSP_ID, USER1, VersionableEntityAction.Read);
454
455     VspDetails vsp =
456         createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
457             "category", "subCategory", "licenseAgreementId",
458             Collections.singletonList("featureGroupId"));
459     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
460     OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(VSP_ID, VERSION01);
461     uploadData.setContentData(
462         ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition"))));
463     doReturn(uploadData).when(orchestrationTemplateDataDaoMock)
464         .get(anyObject(), anyObject());
465     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(),
466         "MainServiceTemplate.yaml"))
467         .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01);
468
469     ValidationResponse validationResponse =
470         vendorSoftwareProductManager.validate(vsp);
471     Assert.assertNotNull(validationResponse);
472     Assert.assertFalse(validationResponse.isValid());
473     Assert.assertNull(validationResponse.getVspErrors());
474     Assert.assertEquals(validationResponse.getLicensingDataErrors().size(), 1);
475
476     verify(versioningManagerMock, never())
477         .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
478             USER1, null);
479   }
480
481   // TODO: 3/15/2017 fix and enable
482   //@Test
483   public void testSubmit() throws IOException {
484     mockVersioning(VersionableEntityAction.Read);
485
486     EnrichmentManagerFactory.getInstance();
487     AbstractFactoryBase
488         .registerFactory(EnrichmentManagerFactory.class, EnrichmentManagerFactoryImpl.class);
489
490     VspDetails vsp =
491         createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
492             "category", "subCategory", "123", Collections.singletonList("fg1"));
493     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
494     OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(VSP_ID, VERSION01);
495     uploadData.setContentData(
496         ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition"))));
497     doReturn(uploadData).when(orchestrationTemplateDataDaoMock)
498         .get(anyObject(), anyObject());
499     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(),
500         "MainServiceTemplate.yaml"))
501         .when(serviceModelDaoMock).getServiceModel(VSP_ID, VERSION01);
502
503     ValidationResponse validationResponse =
504         vendorSoftwareProductManager.validate(vsp);
505     Assert.assertTrue(validationResponse.isValid());
506
507 /*    Assert.assertEquals(vsp2.getVersionInfo().getVersion(), VERSION10);
508     Assert.assertEquals(vsp2.getVersionInfo().getStatus(), VersionStatus.Certified);
509     Assert.assertNull(vsp2.getVersionInfo().getLockingUser());*/
510
511     verify(versioningManagerMock)
512         .submit(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID,
513             USER1, null);
514   }
515
516   @Test
517   public void testCreatePackage() throws IOException {
518     /*VspDetails vspDetailsMock = new VspDetails("vspId", new Version(1, 0));
519     doReturn(vspDetailsMock).when(vspInfoDaoMock).get(anyObject());*/
520     VersionInfo versionInfo = new VersionInfo();
521     versionInfo.setActiveVersion(VERSION10);
522     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
523         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
524         VersionableEntityAction.Read);
525
526     doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), "")).when
527         (enrichedServiceModelDaoMock).getServiceModel(VSP_ID, VERSION10);
528     doNothing().when(vendorSoftwareProductManager).populateVersionsForVlm(anyObject(), anyObject());
529     VspDetails vsp = new VspDetails(VSP_ID, VERSION10);
530     vsp.setVendorId("vendorId");
531     vsp.setVlmVersion(VERSION10);
532     vsp.setFeatureGroups(Arrays.asList("fg1", "fg2"));
533     doReturn(vsp).when(vspInfoDaoMock).get(any(VspDetails.class));
534
535     doReturn(new FileContentHandler()).when(licenseArtifactsServiceMock)
536         .createLicenseArtifacts(VSP_ID, vsp.getVendorId(), VERSION10, vsp.getFeatureGroups()
537         );
538
539     PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(VSP_ID, VERSION10);
540     Assert.assertNotNull(packageInfo.getVspId());
541   }
542
543   // TODO: 3/15/2017 fix and enable
544   //@Test(dependsOnMethods = {"testListFinals"})
545   public void testUploadFileMissingFile() throws IOException {
546     try (InputStream zis = getFileInputStream("/vspmanager/zips/missingYml.zip")) {
547
548       UploadFileResponse uploadFileResponse =
549           candidateManager.upload(VSP_ID, VERSION01, zis, "zip", "file");
550
551       Assert.assertEquals(uploadFileResponse.getErrors().size(), 0);
552     }
553   }
554
555   // TODO: 3/15/2017 fix and enable
556   //@Test(dependsOnMethods = {"testUploadFileMissingFile"})
557   public void testUploadNotZipFile() {
558     URL url = this.getClass().getResource("/notZipFile");
559
560     try {
561       candidateManager.upload(VSP_ID, VERSION01, url.openStream(), "zip", "file");
562       candidateManager.process(VSP_ID, VERSION01);
563     } catch (Exception ce) {
564       Assert.assertEquals(ce.getMessage(), Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage());
565     }
566   }
567
568   private List<String> getWantedFileNamesFromCsar(String pathInCsar)
569       throws IOException {
570     File translatedFile = vendorSoftwareProductManager.getTranslatedFile(VSP_ID, VERSION10);
571
572     return getFileNamesFromFolderInCsar(translatedFile,
573         pathInCsar);
574   }
575
576   private List<String> getFileNamesFromFolderInCsar(File csar, String folderName)
577       throws IOException {
578     List<String> fileNames = new ArrayList<>();
579
580     try (ZipInputStream zip = new ZipInputStream(new FileInputStream(csar))) {
581       ZipEntry ze;
582
583       while ((ze = zip.getNextEntry()) != null) {
584         String name = ze.getName();
585         if (name.contains(folderName)) {
586           fileNames.add(name);
587         }
588       }
589     }
590
591     return fileNames;
592   }
593   /*
594   //Disabled for sonar null pointer issue for componentEntities
595   private Pair<String, String> uploadMib(String vspId, String user, String filePath,
596                                          String fileName) {
597     List<ComponentEntity> componentEntities = null;
598     //(List<ComponentEntity>) vendorSoftwareProductManager.listComponents(vspId, null, user);
599     monitoringUploadsManager.upload(getFileInputStream(filePath),
600         fileName, vspId,
601 <<<<<<< HEAD
602         VERSION01, componentEntities.get(0).getId(), ArtifactType.SNMP_POLL);
603     //TODO: add validate of logActivity() func call
604 =======
605         VERSION01, componentEntities.get(0).getId(), MonitoringUploadType.SNMP_POLL, user);
606     //TODO: add validate of addActionLog() func call
607 >>>>>>> feature/Amdocs-ASDC-1710
608
609     return new ImmutablePair<>(componentEntities.get(0).getId(),
610         componentEntities.get(0).getComponentCompositionData()
611             .getDisplayName());
612   }*/
613
614   // TODO: 3/15/2017 fix and enable
615 /*
616
617   public void testUpdatedVSPShouldBeInBeginningOfList() {
618     vendorSoftwareProductManager.updateVsp(new VspDetails(), USER3);
619     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
620
621     InputStream zis = getFileInputStream("/vspmanager/zips/fullComposition.zip");
622     candidateManager.upload(id007, VERSION01, zis, USER3);
623     candidateManager.process(id007, VERSION01, USER3);
624     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
625   }
626
627   @Test(dependsOnMethods = {"testUpdatedVSPShouldBeInBeginningOfList"})
628   public void testVSPInBeginningOfListAfterCheckin() {
629     vendorSoftwareProductManager.checkin(id006, USER3);
630     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
631
632     vendorSoftwareProductManager.checkin(id007, USER3);
633     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
634   }
635
636   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterCheckin"})
637   public void testVSPInBeginningOfListAfterCheckout() {
638     vendorSoftwareProductManager.checkout(id006, USER3);
639     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
640   }
641
642   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterCheckout"})
643   public void testVSPInBeginningOfListAfterUndoCheckout() {
644     vendorSoftwareProductManager.checkout(id007, USER3);
645     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
646
647     vendorSoftwareProductManager.undoCheckout(id006, USER3);
648     assertVSPInWantedLocationInVSPList(id006, 0, USER3);
649   }
650
651   @Test(dependsOnMethods = {"testVSPInBeginningOfListAfterUndoCheckout"})
652   public void testVSPInBeginningOfListAfterSubmit() throws IOException {
653     vendorSoftwareProductManager.checkin(id007, USER3);
654     vendorSoftwareProductManager.submit(id007, USER3);
655
656     assertVSPInWantedLocationInVSPList(id007, 0, USER3);
657   }
658 */
659   @Test
660   public void testValidateWithCandidateDataNotProcessed() throws IOException {
661     VspDetails vsp =
662         createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-vsp", "vendorName", "vlm1Id", "icon",
663             "category", "subCategory", "licenseAgreementId",
664             Collections.singletonList("featureGroupId"));
665     vsp.setOnboardingMethod("NetworkPackage");
666     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
667
668     OrchestrationTemplateCandidateData orchestrationTemplateCandidateData = new
669         OrchestrationTemplateCandidateData();
670     orchestrationTemplateCandidateData.setFileSuffix("zip");
671     orchestrationTemplateCandidateData.setFilesDataStructure("testdata");
672     orchestrationTemplateCandidateData.setValidationData("");
673     doReturn(Optional.of(orchestrationTemplateCandidateData))
674         .when(orchestrationTemplateCandidateManagerMock)
675         .getInfo(VSP_ID, VERSION01);
676     ValidationResponse validationResponse =
677         vendorSoftwareProductManager.validate(vsp);
678     Assert.assertNotNull(validationResponse);
679     Assert.assertFalse(validationResponse.isValid());
680     Assert.assertNotNull(validationResponse.getVspErrors());
681     Assert.assertEquals(validationResponse.getVspErrors().size(), 1);
682
683   }
684
685   @Test
686   public void testValidateWithCandidateProcessedIsInvalid() throws IOException {
687     VspDetails vsp = createVspDetails(VSP_ID, VERSION01, "Vsp1", "Test-VSP", "vendorName",
688         "vl1Id", "icond", "category", "subcategory", "licenseAgreementId", Collections
689             .singletonList("featureGroupId"));
690     vsp.setOnboardingMethod("NetworkPackage");
691     doReturn(vsp).when(vspInfoDaoMock).get(anyObject());
692
693     OrchestrationTemplateCandidateData orchestrationTemplateCandidateData = new
694         OrchestrationTemplateCandidateData();
695     orchestrationTemplateCandidateData.setFileSuffix("zip");
696     orchestrationTemplateCandidateData.setValidationData("Invalid processed data");
697     doReturn(Optional.of(orchestrationTemplateCandidateData))
698         .when(orchestrationTemplateCandidateManagerMock)
699         .getInfo(VSP_ID, VERSION01);
700     ValidationResponse validationResponse =
701         vendorSoftwareProductManager.validate(vsp);
702     Assert.assertNotNull(validationResponse);
703     Assert.assertFalse(validationResponse.isValid());
704     Assert.assertNotNull(validationResponse.getVspErrors());
705     Assert.assertEquals(validationResponse.getVspErrors().size(), 1);
706   }
707
708   private void testLegalUpload(String vspId, Version version, InputStream upload, String user) {
709     candidateManager.upload(vspId, VERSION01, upload, "zip", "file");
710     candidateManager.process(vspId, VERSION01);
711
712     OrchestrationTemplateEntity uploadData =
713         orchestrationTemplateDataDaoMock.get(vspId, version);
714     Assert.assertNotNull(uploadData);
715   }
716
717
718   private InputStream getFileInputStream(String fileName) {
719     URL url = this.getClass().getResource(fileName);
720     try {
721       return url.openStream();
722     } catch (IOException exception) {
723       exception.printStackTrace();
724       return null;
725     }
726   }
727
728   private static VspDetails createVspDetails(String id, Version version, String name, String desc,
729                                      String vendorName, String vlm, String icon,
730                                      String category, String subCategory,
731                                      String licenseAgreement, List<String> featureGroups) {
732     VspDetails vspDetails = new VspDetails(id, version);
733     vspDetails.setName(name);
734     vspDetails.setDescription(desc);
735     vspDetails.setIcon(icon);
736     vspDetails.setCategory(category);
737     vspDetails.setSubCategory(subCategory);
738     vspDetails.setVendorName(vendorName);
739     vspDetails.setVendorId(vlm);
740     vspDetails.setVlmVersion(new Version("1, 0"));
741     vspDetails.setLicenseAgreement(licenseAgreement);
742     vspDetails.setFeatureGroups(featureGroups);
743     vspDetails.setOnboardingMethod("HEAT");
744     return vspDetails;
745   }
746
747   private static void assertVspsEquals(VspDetails actual, VspDetails expected) {
748     Assert.assertEquals(actual.getId(), expected.getId());
749     Assert.assertEquals(actual.getVersion(), expected.getVersion());
750     Assert.assertEquals(actual.getName(), expected.getName());
751     Assert.assertEquals(actual.getDescription(), expected.getDescription());
752     Assert.assertEquals(actual.getIcon(), expected.getIcon());
753     Assert.assertEquals(actual.getCategory(), expected.getCategory());
754     Assert.assertEquals(actual.getSubCategory(), expected.getSubCategory());
755     Assert.assertEquals(actual.getVendorName(), expected.getVendorName());
756     Assert.assertEquals(actual.getVendorId(), expected.getVendorId());
757     Assert.assertEquals(actual.getLicenseAgreement(), expected.getLicenseAgreement());
758     Assert.assertEquals(actual.getFeatureGroups(), expected.getFeatureGroups());
759   }
760
761
762   // todo ********************** move to common **************************************
763
764   private void mockVersioning(VersionableEntityAction action) {
765     VersionInfo versionInfo = new VersionInfo();
766     versionInfo.setActiveVersion(VERSION01);
767     doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo(
768         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1,
769         action);
770   }
771
772 }