[SDC] Onboarding 1710 rebase.
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / impl / OrchestrationTemplateCandidateManagerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.vendorsoftwareproduct.impl;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.collections4.MapUtils;
25 import org.openecomp.core.model.dao.ServiceModelDao;
26 import org.openecomp.core.model.types.ServiceElement;
27 import org.openecomp.core.translator.datatypes.TranslatorOutput;
28 import org.openecomp.core.util.UniqueValueUtil;
29 import org.openecomp.core.utilities.file.FileContentHandler;
30 import org.openecomp.core.utilities.file.FileUtils;
31 import org.openecomp.core.utilities.json.JsonUtil;
32 import org.openecomp.sdc.activityLog.ActivityLogManager;
33 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
34 import org.openecomp.sdc.common.errors.CoreException;
35 import org.openecomp.sdc.common.errors.Messages;
36 import org.openecomp.sdc.common.utils.CommonUtil;
37 import org.openecomp.sdc.common.utils.SdcCommon;
38 import org.openecomp.sdc.datatypes.error.ErrorLevel;
39 import org.openecomp.sdc.datatypes.error.ErrorMessage;
40 import org.openecomp.sdc.healing.api.HealingManager;
41 import org.openecomp.sdc.healing.types.HealCode;
42 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
43 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
44 import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
45 import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
46 import org.openecomp.sdc.logging.api.Logger;
47 import org.openecomp.sdc.logging.api.LoggerFactory;
48 import org.openecomp.sdc.logging.api.annotations.Metrics;
49 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
50 import org.openecomp.sdc.logging.types.LoggerServiceName;
51 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
52 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
53 import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil;
54 import org.openecomp.sdc.validation.util.ValidationManagerUtil;
55 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
56 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
57 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao;
58 import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao;
59 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
60 import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao;
61 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
62 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
63 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity;
64 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
65 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity;
66 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
67 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity;
68 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
70 import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFoundErrorBuilder;
71 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor;
72 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
73 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
74 import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder;
75 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
76 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
77 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
79 import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils;
80 import org.openecomp.sdc.versioning.dao.types.Version;
81 import org.openecomp.sdcrests.activitylog.types.ActivityType;
82
83 import java.io.ByteArrayInputStream;
84 import java.io.IOException;
85 import java.io.InputStream;
86 import java.nio.ByteBuffer;
87 import java.util.Collection;
88 import java.util.HashMap;
89 import java.util.List;
90 import java.util.Map;
91 import java.util.Optional;
92
93 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.GENERAL_COMPONENT_ID;
94 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME;
95
96 public class OrchestrationTemplateCandidateManagerImpl
97     implements OrchestrationTemplateCandidateManager {
98   private static final Logger logger =
99       LoggerFactory.getLogger(OrchestrationTemplateCandidateManagerImpl.class);
100   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
101   private VendorSoftwareProductDao vendorSoftwareProductDao;
102   private VendorSoftwareProductInfoDao vspInfoDao;
103   private OrchestrationTemplateDao orchestrationTemplateDataDao;
104   private CandidateService candidateService;
105   private HealingManager healingManager;
106   private CompositionDataExtractor compositionDataExtractor;
107   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao;
108   private CompositionEntityDataManager compositionEntityDataManager;
109   private NicDao nicDao;
110   private ComponentDao componentDao;
111   private ComponentArtifactDao componentArtifactDao;
112   private ActivityLogManager activityLogManager;
113   private ProcessDao processDao;
114
115   /**
116    * Instantiates a new Orchestration template candidate manager.
117    *
118    * @param vendorSoftwareProductDao     the vendor software product dao
119    * @param vspInfoDao                   the vsp info dao
120    * @param orchestrationTemplateDataDao the orchestration template data dao
121    * @param candidateService             the candidate service
122    * @param healingManager               the healing manager
123    * @param compositionDataExtractor     the composition data extractor
124    * @param serviceModelDao              the service model dao
125    * @param compositionEntityDataManager the composition entity data manager
126    * @param nicDao                       the nic dao
127    * @param componentDao                 the component dao
128    * @param componentArtifactDao                       the mib dao
129    * @param processDao                   the process dao
130    * @param activityLogManager           the activity log manager
131    */
132   public OrchestrationTemplateCandidateManagerImpl(
133       VendorSoftwareProductDao vendorSoftwareProductDao, VendorSoftwareProductInfoDao
134       vspInfoDao,
135       OrchestrationTemplateDao orchestrationTemplateDataDao,
136       CandidateService candidateService, HealingManager healingManager,
137       CompositionDataExtractor compositionDataExtractor,
138       ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao,
139       CompositionEntityDataManager compositionEntityDataManager,
140       NicDao nicDao,
141       ComponentDao componentDao,
142       ComponentArtifactDao componentArtifactDao,
143       ProcessDao processDao,
144       ActivityLogManager activityLogManager) {
145     this.vendorSoftwareProductDao = vendorSoftwareProductDao;
146     this.vspInfoDao = vspInfoDao;
147     this.orchestrationTemplateDataDao = orchestrationTemplateDataDao;
148     this.candidateService = candidateService;
149     this.healingManager = healingManager;
150     this.compositionDataExtractor = compositionDataExtractor;
151     this.serviceModelDao = serviceModelDao;
152     this.compositionEntityDataManager = compositionEntityDataManager;
153     this.nicDao = nicDao;
154     this.componentDao = componentDao;
155     this.componentArtifactDao = componentArtifactDao;
156     this.processDao = processDao;
157     this.activityLogManager = activityLogManager;
158   }
159
160   @Override
161   @Metrics
162   public UploadFileResponse upload(String vspId, Version version, InputStream heatFileToUpload,
163                                    String user) {
164     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
165
166     VspDetails vspDetails = getVspDetails(vspId, version);
167
168     UploadFileResponse uploadFileResponse = new UploadFileResponse();
169     if (isNotEmptyFileToUpload(heatFileToUpload, uploadFileResponse)) {
170       return uploadFileResponse;
171     }
172
173     byte[] uploadedFileData = FileUtils.toByteArray(heatFileToUpload);
174     if (isInvalidRawZipData(uploadFileResponse, uploadedFileData)) {
175       return uploadFileResponse;
176     }
177
178     Optional<FileContentHandler> optionalContentMap =
179         getZipContentMap(uploadFileResponse, uploadedFileData);
180     if (!optionalContentMap.isPresent()) {
181       logger.error(Messages.ZIP_CONTENT_MAP.getErrorMessage());
182       uploadFileResponse
183           .addStructureError(
184               SdcCommon.UPLOAD_FILE,
185               new ErrorMessage(ErrorLevel.ERROR, Messages.ZIP_CONTENT_MAP.getErrorMessage()));
186
187       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
188       return uploadFileResponse;
189     }
190
191     if (!MapUtils.isEmpty(uploadFileResponse.getErrors())) {
192
193       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
194       return uploadFileResponse;
195     }
196     try {
197       OrchestrationTemplateCandidateData candidateData =
198           new CandidateEntityBuilder(candidateService)
199               .buildCandidateEntityFromZip(vspDetails, uploadedFileData, optionalContentMap.get(),
200                   uploadFileResponse.getErrors(), user);
201       candidateService.updateCandidateUploadData(candidateData, vspDetails.getId());
202     } catch (Exception exception) {
203       logger.error(Messages.ZIP_CONTENT_MAP.getErrorMessage());
204       uploadFileResponse
205           .addStructureError(
206               SdcCommon.UPLOAD_FILE,
207               new ErrorMessage(ErrorLevel.ERROR, exception.getMessage()));
208
209       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
210       return uploadFileResponse;
211     }
212
213     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
214     return uploadFileResponse;
215   }
216
217   @Override
218   public OrchestrationTemplateActionResponse process(String vspId,
219                                                      Version version, String user) {
220     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
221
222     Optional<OrchestrationTemplateCandidateData> candidate =
223         fetchCandidateDataEntity(vspId, version);
224     if (!candidate.isPresent()) {
225       throw new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build());
226     }
227
228     OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
229     UploadFileResponse uploadFileResponse = new UploadFileResponse();
230     OrchestrationTemplateCandidateData candidateDataEntity = candidate.get();
231     Optional<FileContentHandler> fileContent =
232         getZipContentMap(uploadFileResponse, candidateDataEntity.getContentData().array());
233     if (!fileContent.isPresent()) {
234       response.addStructureErrors(uploadFileResponse.getErrors());
235       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
236       return response;
237     }
238
239     Map<String, List<ErrorMessage>> uploadErrors = uploadFileResponse.getErrors();
240     FileContentHandler fileContentMap = fileContent.get();
241     FilesDataStructure structure =
242         JsonUtil.json2Object(candidateDataEntity.getFilesDataStructure(), FilesDataStructure.class);
243
244     if (CollectionUtils.isNotEmpty(structure.getUnassigned())) {
245       response.addErrorMessageToMap(SdcCommon.UPLOAD_FILE,
246           Messages.FOUND_UNASSIGNED_FILES.getErrorMessage(), ErrorLevel.ERROR);
247
248       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
249       return response;
250     }
251
252     VspDetails vspDetails =
253         getVspDetails(vspId, version);
254
255     String manifest = candidateService.createManifest(vspDetails, structure);
256     fileContentMap.addFile(SdcCommon.MANIFEST_NAME, manifest.getBytes());
257
258     Optional<ByteArrayInputStream> zipByteArrayInputStream = candidateService
259         .fetchZipFileByteArrayInputStream(vspId, candidateDataEntity, manifest, uploadErrors);
260     if (!zipByteArrayInputStream.isPresent()) {
261       return response;
262     }
263
264     HeatStructureTree tree = createAndValidateHeatTree(response, fileContentMap);
265
266     Map<String, String> componentsQuestionnaire = new HashMap<>();
267     Map<String, Map<String, String>> componentNicsQuestionnaire = new HashMap<>();
268     Map<String, Collection<ComponentMonitoringUploadEntity>> componentMibList = new HashMap<>();
269     Map<String, Collection<ProcessEntity>> processes = new HashMap<>();
270     Map<String, ProcessEntity> processArtifact = new HashMap<>();
271
272     backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQuestionnaire,
273         componentNicsQuestionnaire, componentMibList, processes, processArtifact);
274
275     deleteUploadDataAndContent(vspId, version);
276     saveHotData(vspId, version, zipByteArrayInputStream.get(), fileContentMap, tree);
277
278     TranslatorOutput translatorOutput =
279         HeatToToscaUtil.loadAndTranslateTemplateData(fileContentMap);
280     ToscaServiceModel toscaServiceModel = translatorOutput.getToscaServiceModel();
281     if (toscaServiceModel != null) {
282       serviceModelDao.storeServiceModel(vspId, version, toscaServiceModel);
283       //Extracting the compostion data from the output service model of the first phase of
284       // translation
285       compositionEntityDataManager.saveCompositionData(vspId, version,
286           compositionDataExtractor.extractServiceCompositionData(translatorOutput
287               .getNonUnifiedToscaServiceModel()));
288       retainComponentQuestionnaireData(vspId, version, componentsQuestionnaire,
289           componentNicsQuestionnaire, componentMibList, processes, processArtifact);
290     }
291     uploadFileResponse.addStructureErrors(uploadErrors);
292
293     ActivityLogEntity activityLogEntity =
294         new ActivityLogEntity(vspId, String.valueOf(version.getMajor() + 1),
295             ActivityType.UPLOAD_HEAT.toString(), user, true, "", "");
296     activityLogManager.addActionLog(activityLogEntity, user);
297
298     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
299     return response;
300   }
301
302
303   @Override
304   public Optional<FilesDataStructure> getFilesDataStructure(
305       String vspId, Version version, String user) {
306     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
307
308     Optional<FilesDataStructure> candidateFileDataStructure =
309         candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version);
310     if (candidateFileDataStructure.isPresent()) {
311       return candidateFileDataStructure;
312     } else {
313       Map<String, Object> healingParams = getHealingParamsAsMap(vspId, version, user);
314
315       mdcDataDebugMessage
316           .debugExitMessage("VSP id", vspId);
317       return (Optional<FilesDataStructure>) healingManager
318           .heal(HealCode.FILE_DATA_STRUCTURE_HEALER, healingParams);
319     }
320   }
321
322   @Override
323
324   public ValidationResponse updateFilesDataStructure(String vspId,
325                                                      Version version, String user,
326                                                      FilesDataStructure fileDataStructure) {
327     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
328
329     ValidationResponse response = new ValidationResponse();
330     Optional<List<ErrorMessage>> validateErrors =
331         candidateService.validateFileDataStructure(fileDataStructure);
332     if (validateErrors.isPresent()) {
333       List<ErrorMessage> errorMessages = validateErrors.get();
334       if (CollectionUtils.isNotEmpty(errorMessages)) {
335         Map<String, List<ErrorMessage>> errorsMap = new HashMap<>();
336         errorsMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
337         response.setUploadDataErrors(errorsMap, LoggerServiceName.Update_Manifest,
338             LoggerTragetServiceName.VALIDATE_FILE_DATA_STRUCTURE);
339
340         mdcDataDebugMessage
341             .debugExitMessage("VSP id", vspId);
342         return response;
343       }
344     }
345     candidateService.updateOrchestrationTemplateCandidateFileDataStructure(vspId, version,
346         fileDataStructure);
347
348     mdcDataDebugMessage
349         .debugExitMessage("VSP id", vspId);
350     return response;
351   }
352
353   @Override
354
355   public Optional<byte[]> get(String vspId, Version version, String user)
356       throws IOException {
357     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
358
359     VspDetails vspDetails =
360         getVspDetails(vspId, version);
361
362     Optional<OrchestrationTemplateCandidateData> candidateDataEntity =
363         fetchCandidateDataEntity(vspId, version);
364
365     if (!candidateDataEntity.isPresent()) {
366       ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
367           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage());
368       logger.error(errorMessage.getMessage());
369
370       mdcDataDebugMessage
371           .debugExitMessage("VSP id", vspId);
372       return Optional.empty();
373     }
374
375     FilesDataStructure structure = JsonUtil
376         .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class);
377     String manifest = candidateService.createManifest(vspDetails, structure);
378
379     mdcDataDebugMessage
380         .debugExitMessage("VSP id", vspId);
381     return Optional.ofNullable(candidateService
382         .replaceManifestInZip(candidateDataEntity.get().getContentData(), manifest, vspId));
383   }
384
385   private Optional<OrchestrationTemplateCandidateData> fetchCandidateDataEntity(
386       String vspId, Version version) {
387     return Optional
388         .ofNullable(candidateService.getOrchestrationTemplateCandidate(vspId, version));
389   }
390
391   private void retainComponentQuestionnaireData(String vspId, Version activeVersion,
392                                                 Map<String, String> componentsQustanniare,
393                                                 Map<String, Map<String, String>>
394                                                     componentNicsQustanniare,
395                                                 Map<String, Collection<ComponentMonitoringUploadEntity>> componentMibList,
396                                                 Map<String, Collection<ProcessEntity>> processes,
397                                                 Map<String, ProcessEntity> processArtifact) {
398     //VSP processes
399     restoreProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID, processes,
400         processArtifact);
401     Collection<ComponentEntity>
402         components = vendorSoftwareProductDao.listComponents(vspId, activeVersion);
403     components.forEach(componentEntity -> {
404       String componentName = componentEntity.getComponentCompositionData().getName();
405       if (componentsQustanniare.containsKey(componentName)) {
406         componentDao.updateQuestionnaireData(vspId, activeVersion,
407             componentEntity.getId(),
408             componentsQustanniare.get(componentEntity.getComponentCompositionData()
409                 .getName()));
410         if (componentNicsQustanniare.containsKey(componentName)) {
411           Map<String, String> nicsQustanniare = componentNicsQustanniare.get(componentName);
412           Collection<NicEntity>
413               nics =
414               nicDao.list(new NicEntity(vspId, activeVersion, componentEntity.getId(), null));
415           nics.forEach(nicEntity -> {
416             if (nicsQustanniare.containsKey(nicEntity.getNicCompositionData().getName())) {
417               nicDao.updateQuestionnaireData(vspId, activeVersion,
418                   componentEntity.getId(), nicEntity.getId(),
419                   nicsQustanniare.get(nicEntity.getNicCompositionData().getName()));
420             }
421           });
422         }
423         //MIB //todo add for VES_EVENTS
424         if (componentMibList.containsKey(componentName)) {
425           Collection<ComponentMonitoringUploadEntity> mibList =
426               componentMibList.get(componentName);
427           mibList.forEach(mib -> {
428             mib.setComponentId(componentEntity.getId());
429             componentArtifactDao.create(mib);
430           });
431         }
432         //VFC processes
433         restoreProcess(vspId, activeVersion, componentEntity.getId(), componentName, processes,
434             processArtifact);
435       }
436     });
437   }
438
439   private void backupComponentsQuestionnaireBeforeDelete(String vspId, Version activeVersion,
440                                                          Map<String, String> componentsQustanniare,
441                                                          Map<String, Map<String, String>>
442                                                            componentNicsQustanniare,
443                                                          Map<String, Collection<ComponentMonitoringUploadEntity>>
444                                                            componentMibList,
445                                                          Map<String, Collection<ProcessEntity>>
446                                                              componentProcesses,
447                                                          Map<String, ProcessEntity> processArtifact) {
448     //backup VSP processes
449     backupProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID,
450         componentProcesses, processArtifact);
451     Collection<ComponentEntity> componentsCompositionAndQuestionnaire = vendorSoftwareProductDao
452         .listComponentsCompositionAndQuestionnaire(vspId,
453             activeVersion);
454     componentsCompositionAndQuestionnaire.forEach(componentEntity -> {
455       String componentName = componentEntity.getComponentCompositionData().getName();
456       componentsQustanniare.put(componentName, componentEntity
457           .getQuestionnaireData());
458       Collection<NicEntity>
459           nics = nicDao.list(new NicEntity(vspId, activeVersion, componentEntity.getId(), null));
460       //backup mib
461       Collection<ComponentMonitoringUploadEntity> componentMib =
462           componentArtifactDao.listArtifacts(new
463               ComponentMonitoringUploadEntity(vspId, activeVersion, componentEntity.getId(),
464               null));
465       if(CollectionUtils.isNotEmpty(componentMib)){
466         componentMibList.put(componentName,componentMib);
467       }
468
469       //backup component processes
470       backupProcess(vspId, activeVersion, componentEntity.getId(), componentName,
471           componentProcesses, processArtifact);
472       if (CollectionUtils.isNotEmpty(nics)) {
473         Map<String, String> nicsQustanniare = new HashMap<>();
474         nics.forEach(nicEntity -> {
475           NicEntity nic = nicDao.get(new NicEntity(vspId, activeVersion, componentEntity.getId(),
476               nicEntity.getId()));
477           NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, activeVersion,
478               componentEntity.getId(), nicEntity.getId());
479
480           nicsQustanniare
481               .put(nicEntity.getNicCompositionData().getName(),
482                   nicQuestionnaire.getQuestionnaireData());
483         });
484         componentNicsQustanniare.put(componentName, nicsQustanniare);
485       }
486     });
487   }
488
489   private void backupProcess(String vspId, Version activeVersion, String componentId,
490                              String componentName, Map<String,
491       Collection<ProcessEntity>> processes,
492                              Map<String, ProcessEntity> processArtifact) {
493     Collection<ProcessEntity> processList = vendorSoftwareProductDao.listProcesses(vspId,
494         activeVersion, componentId);
495     if (!processList.isEmpty()) {
496       processes.put(componentName, processList);
497       processList.forEach(process -> {
498         //ProcessArtifactEntity artifact = vendorSoftwareProductDao.getProcessArtifact(vspId,
499         //    activeVersion, componentId, process.getId());
500         ProcessEntity artifact =
501             processDao.get(new ProcessEntity(vspId, activeVersion, componentId, process.getId()));
502         if (artifact.getArtifact() != null) {
503           processArtifact.put(process.getId(), artifact);
504         }
505       });
506     }
507   }
508
509   private void restoreProcess(String vspId, Version activeVersion, String componentId,
510                               String componentName,
511                               Map<String, Collection<ProcessEntity>> processes,
512                               Map<String, ProcessEntity> processArtifact) {
513     if (processes.containsKey(componentName)) {
514       Collection<ProcessEntity> processList = processes.get(componentName);
515       processList.forEach(process -> {
516         //Reatin VFC process
517         if (!GENERAL_COMPONENT_ID.equals(componentId) && processArtifact.containsKey(process.getId
518             ())) {
519           ProcessEntity artifact = processArtifact.get(process.getId());
520           artifact.setComponentId(componentId);
521           UniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, activeVersion.toString(),
522               componentId, process.getName());
523           vendorSoftwareProductDao.createProcess(artifact);
524         }
525       });
526     }
527   }
528
529   private HeatStructureTree createAndValidateHeatTree(OrchestrationTemplateActionResponse response,
530                                                       FileContentHandler fileContentMap) {
531     VendorSoftwareProductUtils.addFileNamesToUploadFileResponse(fileContentMap, response);
532     Map<String, List<ErrorMessage>> validationErrors =
533         ValidationManagerUtil.initValidationManager(fileContentMap).validate();
534     response.getErrors().putAll(validationErrors);
535
536     HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileContentMap);
537     heatTreeManager.createTree();
538     heatTreeManager.addErrors(validationErrors);
539     return heatTreeManager.getTree();
540   }
541
542   private void saveHotData(String vspId, Version activeVersion, InputStream uploadedFileData,
543                            FileContentHandler fileContentMap, HeatStructureTree tree) {
544     Map<String, Object> manifestAsMap =
545         (Map<String, Object>) JsonUtil.json2Object(fileContentMap.getFileContent(
546             SdcCommon.MANIFEST_NAME), Map.class);
547
548     UploadData uploadData = new UploadData();
549     uploadData.setPackageName((String) manifestAsMap.get("name"));
550     uploadData.setPackageVersion((String) manifestAsMap.get("version"));
551     uploadData.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(uploadedFileData)));
552     uploadData.setValidationDataStructure(new ValidationStructureList(tree));
553     orchestrationTemplateDataDao.updateOrchestrationTemplateData(vspId, uploadData);
554   }
555
556   private void deleteUploadDataAndContent(String vspId, Version version) {
557     //fixme change this when more tables are zusammenized
558     vendorSoftwareProductDao.deleteUploadData(vspId, version);
559   }
560
561   private boolean isInvalidRawZipData(UploadFileResponse uploadFileResponse,
562                                       byte[] uploadedFileData) {
563     Optional<ErrorMessage> errorMessage;
564     errorMessage = candidateService.validateRawZipData(uploadedFileData);
565     if (errorMessage.isPresent()) {
566       uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get());
567       return true;
568     }
569     return false;
570   }
571
572   private boolean isNotEmptyFileToUpload(InputStream heatFileToUpload,
573                                          UploadFileResponse uploadFileResponse) {
574     Optional<ErrorMessage> errorMessage =
575         candidateService.validateNonEmptyFileToUpload(heatFileToUpload);
576     if (errorMessage.isPresent()) {
577       uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get());
578       return true;
579     }
580     return false;
581   }
582
583   private Optional<FileContentHandler> getZipContentMap(UploadFileResponse uploadFileResponse,
584                                                         byte[] uploadedFileData) {
585     FileContentHandler contentMap = null;
586     try {
587       contentMap = CommonUtil.validateAndUploadFileContent(uploadedFileData);
588     } catch (IOException exception) {
589       uploadFileResponse.addStructureError(
590           SdcCommon.UPLOAD_FILE,
591           new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage()));
592     } catch (CoreException coreException) {
593       uploadFileResponse.addStructureError(
594           SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage()));
595     }
596     return Optional.ofNullable(contentMap);
597   }
598
599   // todo *************************** move to reusable place! *************************
600
601   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) {
602     Map<String, Object> healingParams = new HashMap<>();
603
604     healingParams.put(SdcCommon.VSP_ID, vspId);
605     healingParams.put(SdcCommon.VERSION, version);
606     healingParams.put(SdcCommon.USER, user);
607
608     return healingParams;
609   }
610
611   private VspDetails getVspDetails(String vspId, Version version) {
612     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
613     vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId, version));
614     return vspDetails;
615   }
616
617 }