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