a640354f756e74cf1642bce5eccf0d972cec0dcd
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 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.sdcrests.vsp.rest.services;
18
19 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
20 import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
21 import static org.openecomp.sdc.logging.messages.AuditMessages.SUBMIT_VSP_ERROR;
22 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
23 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.VALIDATION_VSP_NAME;
24 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
25 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
26 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
27 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
28 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
29
30 import org.apache.commons.collections4.MapUtils;
31 import org.openecomp.core.util.UniqueValueUtil;
32 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
33 import org.openecomp.sdc.activitylog.ActivityLogManager;
34 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
35 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
36 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
37 import org.openecomp.sdc.common.errors.CoreException;
38 import org.openecomp.sdc.common.errors.ErrorCode;
39 import org.openecomp.sdc.common.errors.Messages;
40 import org.openecomp.sdc.datatypes.error.ErrorLevel;
41 import org.openecomp.sdc.datatypes.error.ErrorMessage;
42 import org.openecomp.sdc.datatypes.model.ItemType;
43 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
44 import org.openecomp.sdc.itempermissions.ItemPermissionsManager;
45 import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory;
46 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
47 import org.openecomp.sdc.logging.api.Logger;
48 import org.openecomp.sdc.logging.api.LoggerFactory;
49 import org.openecomp.sdc.logging.context.MdcUtil;
50 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
51 import org.openecomp.sdc.logging.messages.AuditMessages;
52 import org.openecomp.sdc.logging.types.LoggerConstants;
53 import org.openecomp.sdc.logging.types.LoggerErrorCode;
54 import org.openecomp.sdc.logging.types.LoggerServiceName;
55 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
56 import org.openecomp.sdc.notification.dtos.Event;
57 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
58 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
59 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
60 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
61 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
62 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
63 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
64 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
65 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
66 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
67 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
68 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
69 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
70 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
71 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
72 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
73 import org.openecomp.sdc.versioning.ItemManager;
74 import org.openecomp.sdc.versioning.ItemManagerFactory;
75 import org.openecomp.sdc.versioning.VersioningManager;
76 import org.openecomp.sdc.versioning.VersioningManagerFactory;
77 import org.openecomp.sdc.versioning.dao.types.Version;
78 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
79 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
80 import org.openecomp.sdc.versioning.types.Item;
81 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
82 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
83 import org.openecomp.sdcrests.item.types.ItemCreationDto;
84 import org.openecomp.sdcrests.item.types.VersionDto;
85 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
86 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
87 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
88 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
89 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
90 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
91 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
92 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
93 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
94 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
95 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
96 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
97 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
98 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
99 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
100 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
101 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
102 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
103 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
104 import org.springframework.context.annotation.Scope;
105 import org.springframework.stereotype.Service;
106
107 import javax.inject.Named;
108 import javax.ws.rs.core.Response;
109 import java.io.File;
110 import java.io.IOException;
111 import java.util.Collection;
112 import java.util.Comparator;
113 import java.util.HashMap;
114 import java.util.List;
115 import java.util.Map;
116 import java.util.Optional;
117 import java.util.function.Predicate;
118
119
120 @Named
121 @Service("vendorSoftwareProducts")
122 @Scope(value = "prototype")
123 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
124
125   private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
126   private static final String ATTACHMENT_FILENAME = "attachment; filename=";
127   private static final String SUBMIT_HEALED_VERSION_ERROR =
128       "VSP Id %s: Error while submitting version %s created based on Certified version %s for healing purpose.";
129   private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
130
131   private static ItemCreationDto validationVsp;
132
133   private final ItemManager itemManager = ItemManagerFactory.getInstance().createInterface();
134   private final ItemPermissionsManager permissionsManager =
135       ItemPermissionsManagerFactory.getInstance().createInterface();
136   private final VersioningManager versioningManager =
137       VersioningManagerFactory.getInstance().createInterface();
138   private final VendorSoftwareProductManager vendorSoftwareProductManager =
139       VspManagerFactory.getInstance().createInterface();
140   private final ActivityLogManager activityLogManager =
141       ActivityLogManagerFactory.getInstance().createInterface();
142   private final NotificationPropagationManager notifier =
143       NotificationPropagationManagerFactory.getInstance().createInterface();
144
145   @Override
146   public Response createVsp(VspRequestDto vspRequestDto, String user) {
147     MdcUtil.initMdc(LoggerServiceName.Create_VSP.toString());
148     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_VSP + vspRequestDto.getName());
149
150     OnboardingMethod onboardingMethod = null;
151     try {
152       onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
153     } catch (IllegalArgumentException e) {
154         throwUnknownOnboardingMethodException();
155     }
156     ItemCreationDto itemCreationDto =  null;
157     if (onboardingMethod == OnboardingMethod.NetworkPackage
158             || onboardingMethod == OnboardingMethod.Manual) {
159       itemCreationDto = getItemCreationDto(vspRequestDto, user, onboardingMethod);
160
161     } else {
162        throwUnknownOnboardingMethodException();
163     }
164
165     return Response.ok(itemCreationDto).build();
166   }
167
168   private ItemCreationDto getItemCreationDto(VspRequestDto vspRequestDto,
169                                              String user,
170                                              OnboardingMethod onboardingMethod) {
171
172     Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
173     item.setType(ItemType.vsp.name());
174     item.setOwner(user);
175     item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
176
177     UniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
178     item = itemManager.create(item);
179     UniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
180
181     Version version = versioningManager.create(item.getId(), new Version(), null);
182
183     VspDetails vspDetails =
184             new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
185     vspDetails.setId(item.getId());
186     vspDetails.setVersion(version);
187     vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
188
189     vendorSoftwareProductManager.createVsp(vspDetails);
190     versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
191     ItemCreationDto itemCreationDto = new ItemCreationDto();
192     itemCreationDto.setItemId(item.getId());
193     itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
194
195     activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version,
196             ActivityType.Create, user, true, "", ""));
197     return itemCreationDto;
198   }
199
200   private void throwUnknownOnboardingMethodException() {
201     ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder
202         .getInvalidOnboardingMethodErrorBuilder();
203     MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
204         LoggerTragetServiceName.ADD_VSP, ErrorLevel.ERROR.name(),
205         LoggerErrorCode.DATA_ERROR.getErrorCode(), onboardingMethodUpdateErrorCode.message());
206     throw  new CoreException(onboardingMethodUpdateErrorCode);
207   }
208
209   @Override
210   public Response listVsps(String versionStatus, String user) {
211     MdcUtil.initMdc(LoggerServiceName.List_VSP.toString());
212
213     Predicate<Item> itemPredicate;
214     if (VersionStatus.Certified.name().equals(versionStatus)) {
215       itemPredicate = item -> ItemType.vsp.name().equals(item.getType())
216               && item.getVersionStatusCounters().containsKey(VersionStatus.Certified);
217
218     } else if (VersionStatus.Draft.name().equals(versionStatus)) {
219       itemPredicate = item -> ItemType.vsp.name().equals(item.getType())
220               && item.getVersionStatusCounters().containsKey(VersionStatus.Draft)
221               && userHasPermission(item.getId(), user);
222
223     } else {
224       itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
225     }
226
227     GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
228     MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
229     itemManager.list(itemPredicate).stream()
230         .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
231         .forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
232
233     return Response.ok(results).build();
234   }
235
236   @Override
237   public Response getVsp(String vspId, String versionId, String user) {
238     MdcUtil.initMdc(LoggerServiceName.Get_VSP.toString());
239
240     Version version = versioningManager.get(vspId, new Version(versionId));
241     VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
242     vspDetails.setWritetimeMicroSeconds(version.getModificationTime().getTime());
243
244     try {
245       Optional<Version> healedVersion = HealingManagerFactory.getInstance().createInterface()
246           .healItemVersion(vspId, version, ItemType.vsp, false);
247
248       healedVersion.ifPresent(version1 -> {
249         vspDetails.setVersion(version1);
250         if (version.getStatus() == VersionStatus.Certified) {
251           submitHealedVersion(vspId, version1, versionId, user);
252         }
253       });
254     } catch (Exception e) {
255       LOGGER.error(
256           String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId),
257           e);
258     }
259
260     VspDetailsDto vspDetailsDto =
261         new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
262     addNetworkPackageInfo(vspId, version, vspDetailsDto);
263
264     return Response.ok(vspDetailsDto).build();
265   }
266
267   private void submitHealedVersion(String vspId, Version healedVersion, String baseVersionId,
268                                    String user) {
269     try {
270       Optional<ValidationResponse>
271           validationResponse = submit(vspId, healedVersion, "Submit healed Vsp", user);
272       // TODO: 8/9/2017 before collaboration checkout was done at this scenario (equivalent
273       // to new version in collaboration). need to decide what should be done now.
274       validationResponse.ifPresent(validationResponse1 -> {
275         throw new IllegalStateException("Certified vsp after healing failed on validation");
276       });
277       vendorSoftwareProductManager.createPackage(vspId, healedVersion);
278     } catch (Exception ex) {
279       LOGGER.error(
280           String.format(SUBMIT_HEALED_VERSION_ERROR, vspId, healedVersion.getId(), baseVersionId),
281           ex);
282     }
283   }
284
285   @Override
286   public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto,
287                             String user) {
288     MdcUtil.initMdc(LoggerServiceName.Update_VSP.toString());
289     VspDetails vspDetails =
290         new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
291     vspDetails.setId(vspId);
292     vspDetails.setVersion(new Version(versionId));
293
294     vendorSoftwareProductManager.updateVsp(vspDetails);
295
296     return Response.ok().build();
297   }
298
299   @Override
300   public Response deleteVsp(String vspId, String user) {
301     MdcUtil.initMdc(LoggerServiceName.Delete_VSP.toString());
302     vendorSoftwareProductManager.deleteVsp(vspId);
303
304     return Response.ok().build();
305   }
306
307   @Override
308   public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request,
309                                              String vspId, String versionId,
310                                              String user) throws IOException {
311     Version version = new Version(versionId);
312
313     if (request.getAction() == VendorSoftwareProductAction.Submit) {
314       if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
315         return Response.status(Response.Status.FORBIDDEN)
316                 .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
317       }
318       String message = request.getSubmitRequest() == null ? "Submit"
319               : request.getSubmitRequest().getMessage();
320       Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
321
322       if (validationResponse.isPresent()) {
323         ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
324                 .applyMapping(validationResponse.get(), ValidationResponseDto.class);
325         return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto)
326                 .build();
327       }
328
329       notifyUsers(vspId, version, message, user, NotificationEventTypes.SUBMIT);
330
331     } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
332       return createPackage(vspId, version);
333     }
334
335     return Response.ok().build();
336   }
337
338   @Override
339   public Response getValidationVsp(String user) throws Exception {
340     if (validationVsp != null) {
341       return Response.ok(validationVsp).build();
342     }
343
344     VspRequestDto validationVspRequest = new VspRequestDto();
345     validationVspRequest.setOnboardingMethod("HEAT");
346     validationVspRequest.setName(VALIDATION_VSP_NAME);
347
348     try {
349       validationVsp = (ItemCreationDto) createVsp(validationVspRequest, user).getEntity();
350       return Response.ok(validationVsp).build();
351
352     } catch (CoreException validationVspAlreadyExistException) {
353       // find validationVsp
354       String validationVspId = itemManager.list(item ->
355           ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME.equals(item.getName()))
356           .stream().findFirst().orElseThrow(() -> new IllegalStateException("Vsp with name %s "
357                 + "does not exist even though the name exists according to unique value util"))
358               .getId();
359       Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
360
361       validationVsp = new ItemCreationDto();
362       validationVsp.setItemId(validationVspId);
363       validationVsp
364           .setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
365
366       return Response.ok(validationVsp).build();
367     }
368   }
369
370   @Override
371   public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
372     MdcUtil.initMdc(LoggerServiceName.Get_Uploaded_File.toString());
373     byte[] orchestrationTemplateFile =
374         vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
375
376     if (orchestrationTemplateFile == null) {
377       return Response.status(Response.Status.NOT_FOUND).build();
378     }
379     Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
380     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
381     return response.build();
382   }
383
384   @Override
385   public Response listPackages(String category, String subCategory, String user) {
386     MdcUtil.initMdc(LoggerServiceName.List_Packages.toString());
387     List<PackageInfo> packageInfoList =
388         vendorSoftwareProductManager.listPackages(category, subCategory);
389
390     GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
391     MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
392
393     if (packageInfoList != null) {
394       for (PackageInfo packageInfo : packageInfoList) {
395         results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
396       }
397     }
398     return Response.ok(results).build();
399   }
400
401   @Override
402   public Response getTranslatedFile(String vspId, String versionName, String user) {
403     MdcUtil.initMdc(LoggerServiceName.Get_Translated_File.toString());
404
405     List<Version> versions = versioningManager.list(vspId);
406     Version version;
407     if (versionName == null) {
408       version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
409           .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName()))).orElseThrow(() -> {
410             MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
411                 LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
412                 LoggerErrorCode.DATA_ERROR.getErrorCode(), "Package not found");
413             return new CoreException(new PackageNotFoundErrorBuilder(vspId).build());
414           });
415     } else {
416       version = versions.stream().filter(ver -> versionName.equals(ver.getName()))
417           .findFirst().orElseThrow(() -> {
418             MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
419                 LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
420                 LoggerErrorCode.DATA_ERROR.getErrorCode(), "Package not found");
421             return new CoreException(new PackageNotFoundErrorBuilder(vspId).build());
422           });
423
424       if (version.getStatus() != VersionStatus.Certified) {
425         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
426             LoggerTragetServiceName.GET_VERSION_INFO, ErrorLevel.ERROR.name(),
427             LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid requested version");
428         throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
429       }
430     }
431
432     File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
433
434     Response.ResponseBuilder response = Response.ok(zipFile);
435     if (zipFile == null) {
436       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId);
437       return Response.status(Response.Status.NOT_FOUND).build();
438     }
439     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
440
441     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId);
442     return response.build();
443   }
444
445   @Override
446   public Response getQuestionnaire(String vspId, String versionId, String user) {
447     MdcUtil.initMdc(LoggerServiceName.Get_Questionnaire_VSP.toString());
448     QuestionnaireResponse questionnaireResponse =
449         vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
450
451     if (questionnaireResponse.getErrorMessage() != null) {
452       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
453           new MapQuestionnaireResponseToQuestionnaireResponseDto()
454               .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build();
455     }
456
457     QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
458         .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
459     return Response.ok(result).build();
460   }
461
462   @Override
463   public Response updateQuestionnaire(String questionnaireData, String vspId, String
464       versionId, String user) {
465     MdcUtil.initMdc(LoggerServiceName.Update_Questionnaire_VSP.toString());
466     vendorSoftwareProductManager
467         .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
468     return Response.ok().build();
469   }
470
471   @Override
472   public Response heal(String vspId, String versionId, String user) {
473     HealingManagerFactory.getInstance().createInterface()
474         .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
475     return Response.ok().build();
476   }
477
478   @Override
479   public Response getVspInformationArtifact(String vspId, String versionId, String user) {
480     MdcUtil.initMdc(LoggerServiceName.Get_Information_Artifact.toString());
481     File textInformationArtifact =
482         vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
483
484     Response.ResponseBuilder response = Response.ok(textInformationArtifact);
485     if (textInformationArtifact == null) {
486       return Response.status(Response.Status.NOT_FOUND).build();
487     }
488     response
489         .header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
490     return response.build();
491   }
492
493   @Override
494   public Response listComputes(String vspId, String version, String user) {
495
496     Collection<ComputeEntity> computes =
497         vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
498
499     MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
500     GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
501     for (ComputeEntity compute : computes) {
502       results.add(mapper.applyMapping(compute, VspComputeDto.class));
503     }
504
505     return Response.ok(results).build();
506   }
507
508   private Optional<ValidationResponse> submit(String vspId, Version version, String message,
509                                               String user) throws IOException {
510     MdcUtil.initMdc(LoggerServiceName.Submit_VSP.toString());
511     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId);
512
513     ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspId, version);
514     Map<String, List<ErrorMessage>> compilationErrors =
515         vendorSoftwareProductManager.compile(vspId, version);
516     if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
517       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP_FAIL + vspId);
518       if (validationResponse.getVspErrors() != null) {
519         validationResponse.getVspErrors().forEach(errorCode -> LOGGER.audit(AuditMessages
520             .AUDIT_MSG + String.format(SUBMIT_VSP_ERROR, errorCode.message(), vspId)));
521       }
522       if (validationResponse.getUploadDataErrors() != null) {
523         validationResponse.getUploadDataErrors().values().forEach(errorMessages
524             -> printAuditForErrors(errorMessages, vspId, SUBMIT_VSP_ERROR));
525       }
526       activityLogManager.logActivity(
527           new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false,
528               "Failed on validation before submit", ""));
529       return Optional.of(validationResponse);
530     }
531
532     versioningManager.submit(vspId, version, message);
533
534     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId);
535     activityLogManager.logActivity(
536         new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
537     return Optional.empty();
538   }
539
540   private void notifyUsers(String itemId, Version version, String message,
541                            String userName, NotificationEventTypes eventType) {
542     Map<String, Object> eventProperties = new HashMap<>();
543     eventProperties.put(ITEM_NAME, itemManager.get(itemId).getName());
544     eventProperties.put(ITEM_ID, itemId);
545
546     Version ver = versioningManager.get(itemId, version);
547     eventProperties.put(VERSION_NAME, ver.getName());
548     eventProperties.put(VERSION_ID, ver.getId());
549
550     eventProperties.put(SUBMIT_DESCRIPTION, message);
551     eventProperties.put(PERMISSION_USER, userName);
552
553     Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
554     try {
555       notifier.notifySubscribers(syncEvent, userName);
556     } catch (Exception e) {
557       LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId);
558     }
559   }
560
561   private class SyncEvent implements Event {
562
563     private final String eventType;
564     private final String originatorId;
565     private final Map<String, Object> attributes;
566     private final String entityId;
567
568      SyncEvent(String eventType, String originatorId,
569                      Map<String, Object> attributes, String entityId) {
570       this.eventType = eventType;
571       this.originatorId = originatorId;
572       this.attributes = attributes;
573       this.entityId = entityId;
574     }
575
576     @Override
577     public String getEventType() {
578       return eventType;
579     }
580
581     @Override
582     public String getOriginatorId() {
583       return originatorId;
584     }
585
586     @Override
587     public Map<String, Object> getAttributes() {
588       return attributes;
589     }
590
591     @Override
592     public String getEntityId() {
593       return entityId;
594     }
595   }
596
597   private Response createPackage(String vspId, Version version) throws IOException {
598     MdcUtil.initMdc(LoggerServiceName.Create_Package.toString());
599
600     Version retrievedVersion = versioningManager.get(vspId, version);
601     if (retrievedVersion.getStatus() != VersionStatus.Certified) {
602       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
603           LoggerTragetServiceName.CREATE_PACKAGE, ErrorLevel.ERROR.name(),
604           LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't create package");
605       throw new CoreException(
606           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
607               .build());
608     }
609     PackageInfo packageInfo =
610         vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
611     return Response.ok(packageInfo == null
612         ? null
613         : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class))
614         .build();
615   }
616
617   private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
618     OrchestrationTemplateEntity orchestrationTemplateInfo =
619         vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
620
621     vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
622     vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
623     vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix() == null
624         ? OnboardingTypesEnum.NONE.toString()
625         : orchestrationTemplateInfo.getFileSuffix());
626
627     OrchestrationTemplateCandidateData candidateInfo =
628         OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
629             .getInfo(vspId, version);
630
631     //todo - remove after fix missing candidate element
632     if (candidateInfo == null) {
633       candidateInfo = new OrchestrationTemplateCandidateData();
634       candidateInfo.setFileSuffix("zip");
635     }
636
637     vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.getFileSuffix() == null
638         ? OnboardingTypesEnum.NONE.toString()
639         : candidateInfo.getFileSuffix());
640   }
641
642   private boolean userHasPermission(String itemId, String userId) {
643     String permission = permissionsManager.getUserItemPermiission(itemId, userId);
644     return permission != null && permission
645         .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name());
646   }
647
648   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
649     errorList.forEach(errorMessage -> {
650       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
651         LOGGER.audit(
652             AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId));
653       }
654     });
655   }
656 }