Merge "Enabled static analysis in Onboarding tests"
[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.lang3.tuple.ImmutablePair;
25 import org.apache.commons.lang3.tuple.Pair;
26 import org.openecomp.core.model.dao.ServiceModelDao;
27 import org.openecomp.core.model.types.ServiceElement;
28 import org.openecomp.core.utilities.json.JsonUtil;
29 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
30 import org.openecomp.sdc.activityLog.ActivityLogManager;
31 import org.openecomp.sdc.common.errors.CoreException;
32 import org.openecomp.sdc.common.errors.Messages;
33 import org.openecomp.sdc.common.utils.CommonUtil;
34 import org.openecomp.sdc.common.utils.SdcCommon;
35 import org.openecomp.sdc.datatypes.error.ErrorLevel;
36 import org.openecomp.sdc.datatypes.error.ErrorMessage;
37 import org.openecomp.sdc.healing.api.HealingManager;
38 import org.openecomp.sdc.healing.types.HealCode;
39 import org.openecomp.sdc.logging.api.Logger;
40 import org.openecomp.sdc.logging.api.LoggerFactory;
41 import org.openecomp.sdc.logging.api.annotations.Metrics;
42 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
43 import org.openecomp.sdc.logging.messages.AuditMessages;
44 import org.openecomp.sdc.logging.types.LoggerServiceName;
45 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
46 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
47 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
49 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao;
50 import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao;
51 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
52 import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao;
53 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
54 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
55 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
56 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
57 import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFoundErrorBuilder;
58 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationTemplateFileHandler;
59 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUploadFactory;
60 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationProcessFactory;
61 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationTemplateProcessHandler;
62 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor;
63 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
64 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
65 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
66 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
67 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
68 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
69 import org.openecomp.sdc.versioning.dao.types.Version;
70
71 import java.io.IOException;
72 import java.io.InputStream;
73 import java.util.HashMap;
74 import java.util.List;
75 import java.util.Map;
76 import java.util.Optional;
77
78 public class OrchestrationTemplateCandidateManagerImpl
79     implements OrchestrationTemplateCandidateManager {
80   private static final Logger logger =
81       LoggerFactory.getLogger(OrchestrationTemplateCandidateManagerImpl.class);
82   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
83   private VendorSoftwareProductDao vendorSoftwareProductDao;
84   private VendorSoftwareProductInfoDao vspInfoDao;
85   private OrchestrationTemplateDao orchestrationTemplateDataDao;
86   private CandidateService candidateService;
87   private HealingManager healingManager;
88   private CompositionDataExtractor compositionDataExtractor;
89   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao;
90   private CompositionEntityDataManager compositionEntityDataManager;
91   private NicDao nicDao;
92   private ComponentDao componentDao;
93   private ComponentArtifactDao componentArtifactDao;
94   private ActivityLogManager activityLogManager;
95   private ProcessDao processDao;
96
97   /**
98    * Instantiates a new Orchestration template candidate manager.
99    *
100    * @param vendorSoftwareProductDao     the vendor software product dao
101    * @param vspInfoDao                   the vsp info dao
102    * @param orchestrationTemplateDataDao the orchestration template data dao
103    * @param candidateService             the candidate service
104    * @param healingManager               the healing manager
105    * @param compositionDataExtractor     the composition data extractor
106    * @param serviceModelDao              the service model dao
107    * @param compositionEntityDataManager the composition entity data manager
108    * @param nicDao                       the nic dao
109    * @param componentDao                 the component dao
110    * @param componentArtifactDao                       the mib dao
111    * @param processDao                   the process dao
112    * @param activityLogManager           the activity log manager
113    */
114   public OrchestrationTemplateCandidateManagerImpl(
115       VendorSoftwareProductDao vendorSoftwareProductDao, VendorSoftwareProductInfoDao
116       vspInfoDao,
117       OrchestrationTemplateDao orchestrationTemplateDataDao,
118       CandidateService candidateService, HealingManager healingManager,
119       CompositionDataExtractor compositionDataExtractor,
120       ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao,
121       CompositionEntityDataManager compositionEntityDataManager,
122       NicDao nicDao,
123       ComponentDao componentDao,
124       ComponentArtifactDao componentArtifactDao,
125       ProcessDao processDao,
126       ActivityLogManager activityLogManager) {
127     this.vendorSoftwareProductDao = vendorSoftwareProductDao;
128     this.vspInfoDao = vspInfoDao;
129     this.orchestrationTemplateDataDao = orchestrationTemplateDataDao;
130     this.candidateService = candidateService;
131     this.healingManager = healingManager;
132     this.compositionDataExtractor = compositionDataExtractor;
133     this.serviceModelDao = serviceModelDao;
134     this.compositionEntityDataManager = compositionEntityDataManager;
135     this.nicDao = nicDao;
136     this.componentDao = componentDao;
137     this.componentArtifactDao = componentArtifactDao;
138     this.processDao = processDao;
139     this.activityLogManager = activityLogManager;
140   }
141
142   @Override
143   @Metrics
144   public UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload,
145                                    String user, String filePrefix,
146                                    String networkPackageName) {
147     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
148     OrchestrationTemplateFileHandler orchestrationTemplateFileHandler =
149             OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(filePrefix);
150     VspDetails vspDetails = getVspDetails(vspId, version);
151     UploadFileResponse uploadResponse = orchestrationTemplateFileHandler
152         .upload(vspId, version, fileToUpload, user, candidateService,
153             vspDetails);
154     vspDetails.setOnboardingOrigin(filePrefix);
155     vspDetails.setNetworkPackageName(networkPackageName);
156     vspInfoDao.update(vspDetails);
157
158     uploadResponse.setNetworkPackageName(networkPackageName);
159     return uploadResponse;
160   }
161
162
163
164   @Override
165   public OrchestrationTemplateActionResponse process(String vspId,
166                                                      Version version, String user) {
167     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
168     OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse();
169
170     Optional<OrchestrationTemplateCandidateData> candidate =
171         fetchCandidateDataEntity(vspId, version);
172     if (!candidate.isPresent()) {
173       throw new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build());
174     }
175
176     VspDetails vspDetails =
177         getVspDetails(vspId, version);
178     Optional<OrchestrationTemplateProcessHandler> processInstance =
179         OrchestrationProcessFactory.getInstance(vspDetails.getOnboardingOrigin());
180
181     if(processInstance.isPresent()){
182       response = processInstance.get().process(vspDetails, candidate.get(), user);
183     }
184
185     return response;
186   }
187
188   @Override
189   public Optional<FilesDataStructure> getFilesDataStructure(
190       String vspId, Version version, String user) {
191     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
192
193     Optional<FilesDataStructure> candidateFileDataStructure =
194         candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version);
195     if (candidateFileDataStructure.isPresent()) {
196       return candidateFileDataStructure;
197     } else {
198       Map<String, Object> healingParams = getHealingParamsAsMap(vspId, version, user);
199
200       mdcDataDebugMessage
201           .debugExitMessage("VSP id", vspId);
202       return (Optional<FilesDataStructure>) healingManager
203           .heal(HealCode.FILE_DATA_STRUCTURE_HEALER, healingParams);
204     }
205   }
206
207   @Override
208
209   public ValidationResponse updateFilesDataStructure(String vspId,
210                                                      Version version, String user,
211                                                      FilesDataStructure fileDataStructure) {
212     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
213
214     ValidationResponse response = new ValidationResponse();
215     Optional<List<ErrorMessage>> validateErrors =
216         candidateService.validateFileDataStructure(fileDataStructure);
217     if (validateErrors.isPresent()) {
218       List<ErrorMessage> errorMessages = validateErrors.get();
219       if (CollectionUtils.isNotEmpty(errorMessages)) {
220         Map<String, List<ErrorMessage>> errorsMap = new HashMap<>();
221         errorsMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
222         response.setUploadDataErrors(errorsMap, LoggerServiceName.Update_Manifest,
223             LoggerTragetServiceName.VALIDATE_FILE_DATA_STRUCTURE);
224
225         mdcDataDebugMessage
226             .debugExitMessage("VSP id", vspId);
227         return response;
228       }
229     }
230     candidateService.updateOrchestrationTemplateCandidateFileDataStructure(vspId, version,
231         fileDataStructure);
232
233     mdcDataDebugMessage
234         .debugExitMessage("VSP id", vspId);
235     return response;
236   }
237
238   @Override
239
240   public Optional<Pair<String, byte[]>> get(String vspId, Version version, String user)
241       throws IOException {
242     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
243
244     VspDetails vspDetails =
245         getVspDetails(vspId, version);
246
247     Optional<OrchestrationTemplateCandidateData> candidateDataEntity =
248         fetchCandidateDataEntity(vspId, version);
249
250     if (!candidateDataEntity.isPresent()) {
251       ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
252           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage());
253       logger.error(errorMessage.getMessage());
254
255       mdcDataDebugMessage
256           .debugExitMessage("VSP id", vspId);
257       return Optional.empty();
258     }
259     OnboardingTypesEnum type =
260         OnboardingTypesEnum.getOnboardingTypesEnum(vspDetails.getOnboardingOrigin());
261
262     if(CommonUtil.isFileOriginFromZip(vspDetails.getOnboardingOrigin())) {
263       FilesDataStructure structure = JsonUtil
264           .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class);
265       String manifest = candidateService.createManifest(vspDetails, structure);
266
267       mdcDataDebugMessage
268           .debugExitMessage("VSP id", vspId);
269       return Optional.of(
270           new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(),candidateService
271               .replaceManifestInZip(candidateDataEntity.get().getContentData(),
272               manifest, vspId, type)));
273     }
274
275     return Optional.of(
276         new ImmutablePair<>(vspDetails.getOnboardingOrigin(),candidateDataEntity.get()
277             .getContentData().array()));
278   }
279
280   private Optional<OrchestrationTemplateCandidateData> fetchCandidateDataEntity(
281       String vspId, Version version) {
282     return Optional
283         .ofNullable(candidateService.getOrchestrationTemplateCandidate(vspId, version));
284   }
285
286
287   // todo *************************** move to reusable place! *************************
288
289   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) {
290     Map<String, Object> healingParams = new HashMap<>();
291
292     healingParams.put(SdcCommon.VSP_ID, vspId);
293     healingParams.put(SdcCommon.VERSION, version);
294     healingParams.put(SdcCommon.USER, user);
295
296     return healingParams;
297   }
298
299   private VspDetails getVspDetails(String vspId, Version version) {
300     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
301     vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId, version));
302     return vspDetails;
303   }
304
305   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
306
307     errorList.forEach(errorMessage -> {
308       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
309         logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(),
310             vspId));
311       }
312     });
313   }
314
315 }