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