Add collaboration feature
[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.utilities.json.JsonUtil;
27 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
28 import org.openecomp.sdc.common.errors.CoreException;
29 import org.openecomp.sdc.common.errors.Messages;
30 import org.openecomp.sdc.common.utils.CommonUtil;
31 import org.openecomp.sdc.common.utils.SdcCommon;
32 import org.openecomp.sdc.datatypes.error.ErrorLevel;
33 import org.openecomp.sdc.datatypes.error.ErrorMessage;
34 import org.openecomp.sdc.healing.api.HealingManager;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37 import org.openecomp.sdc.logging.api.annotations.Metrics;
38 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
39 import org.openecomp.sdc.logging.messages.AuditMessages;
40 import org.openecomp.sdc.logging.types.LoggerServiceName;
41 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
42 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
43 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
44 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
45 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
46 import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFoundErrorBuilder;
47 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationTemplateFileHandler;
48 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUploadFactory;
49 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process.OrchestrationProcessFactory;
50 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
51 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
52 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
53 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
54 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
55 import org.openecomp.sdc.versioning.dao.types.Version;
56
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.util.HashMap;
60 import java.util.List;
61 import java.util.Map;
62 import java.util.Optional;
63
64 public class OrchestrationTemplateCandidateManagerImpl
65     implements OrchestrationTemplateCandidateManager {
66   private static final Logger logger =
67       LoggerFactory.getLogger(OrchestrationTemplateCandidateManagerImpl.class);
68   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
69
70   private VendorSoftwareProductInfoDao vspInfoDao;
71   private CandidateService candidateService;
72   private HealingManager healingManager;
73
74   public OrchestrationTemplateCandidateManagerImpl(VendorSoftwareProductInfoDao vspInfoDao,
75                                                    CandidateService candidateService,
76                                                    HealingManager healingManager) {
77     this.vspInfoDao = vspInfoDao;
78     this.candidateService = candidateService;
79     this.healingManager = healingManager;
80   }
81
82   @Override
83   @Metrics
84   public UploadFileResponse upload(String vspId, Version version, InputStream fileToUpload,
85                                    String fileSuffix, String networkPackageName) {
86     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
87
88     OrchestrationTemplateFileHandler orchestrationTemplateFileHandler =
89         OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(fileSuffix);
90
91     VspDetails vspDetails = getVspDetails(vspId, version);
92
93     UploadFileResponse uploadResponse = orchestrationTemplateFileHandler
94         .upload(vspDetails, fileToUpload, fileSuffix, networkPackageName, candidateService);
95
96     uploadResponse.setNetworkPackageName(networkPackageName);
97     return uploadResponse;
98   }
99
100   @Override
101   public OrchestrationTemplateActionResponse process(String vspId, Version version) {
102     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
103
104     OrchestrationTemplateCandidateData candidate = fetchCandidateDataEntity(vspId, version)
105         .orElseThrow(
106             () -> new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build()));
107
108     return OrchestrationProcessFactory.getInstance(candidate.getFileSuffix())
109         .map(processor -> processor.process(getVspDetails(vspId, version), candidate))
110         .orElse(new OrchestrationTemplateActionResponse());
111   }
112
113   @Override
114   public Optional<FilesDataStructure> getFilesDataStructure(String vspId, Version version) {
115     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
116
117     Optional<FilesDataStructure> candidateFileDataStructure =
118         candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version);
119     if (candidateFileDataStructure.isPresent()) {
120       return candidateFileDataStructure;
121     } else {
122       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
123       return Optional.empty();
124     }
125   }
126
127   @Override
128   public ValidationResponse updateFilesDataStructure(String vspId, Version version,
129                                                      FilesDataStructure fileDataStructure) {
130     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
131
132     ValidationResponse response = new ValidationResponse();
133     Optional<List<ErrorMessage>> validateErrors =
134         candidateService.validateFileDataStructure(fileDataStructure);
135     if (validateErrors.isPresent()) {
136       List<ErrorMessage> errorMessages = validateErrors.get();
137       if (CollectionUtils.isNotEmpty(errorMessages)) {
138         Map<String, List<ErrorMessage>> errorsMap = new HashMap<>();
139         errorsMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
140         response.setUploadDataErrors(errorsMap, LoggerServiceName.Update_Manifest,
141             LoggerTragetServiceName.VALIDATE_FILE_DATA_STRUCTURE);
142
143         mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
144         return response;
145       }
146     }
147     candidateService
148         .updateOrchestrationTemplateCandidateFileDataStructure(vspId, version, fileDataStructure);
149
150     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
151     return response;
152   }
153
154   @Override
155
156   public Optional<Pair<String, byte[]>> get(String vspId, Version version) throws IOException {
157     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
158
159     VspDetails vspDetails = getVspDetails(vspId, version);
160
161     Optional<OrchestrationTemplateCandidateData> candidateDataEntity =
162         fetchCandidateDataEntity(vspId, version);
163
164     if (!candidateDataEntity.isPresent()) {
165       ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
166           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage());
167       logger.error(errorMessage.getMessage());
168
169       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
170       return Optional.empty();
171     }
172     OnboardingTypesEnum type =
173         OnboardingTypesEnum.getOnboardingTypesEnum(candidateDataEntity.get().getFileSuffix());
174
175     if (CommonUtil.isFileOriginFromZip(candidateDataEntity.get().getFileSuffix())) {
176       FilesDataStructure structure = JsonUtil
177           .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class);
178       String manifest = candidateService.createManifest(vspDetails, structure);
179
180       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
181       return Optional.of(
182           new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(), candidateService
183               .replaceManifestInZip(candidateDataEntity.get().getContentData(),
184                   manifest, vspId, type)));
185     }
186
187     return Optional.of(
188         new ImmutablePair<>(candidateDataEntity.get().getFileSuffix(), candidateDataEntity.get()
189             .getContentData().array()));
190   }
191
192   @Override
193   public OrchestrationTemplateCandidateData getInfo(String vspId, Version version) {
194     return candidateService.getOrchestrationTemplateCandidateInfo(vspId, version);
195   }
196
197   private Optional<OrchestrationTemplateCandidateData> fetchCandidateDataEntity(
198       String vspId, Version version) {
199     return Optional
200         .ofNullable(candidateService.getOrchestrationTemplateCandidate(vspId, version));
201   }
202
203
204   // todo *************************** move to reusable place! *************************
205
206   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version) {
207     Map<String, Object> healingParams = new HashMap<>();
208
209     healingParams.put(SdcCommon.VSP_ID, vspId);
210     healingParams.put(SdcCommon.VERSION, version);
211
212     return healingParams;
213   }
214
215   private VspDetails getVspDetails(String vspId, Version version) {
216     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
217 /*    OrchestrationTemplateEntity orchestrationTemplateInfo =
218         orchestrationTemplateDao.getInfo(vspId, version);
219     vspDetails.setValidationData(orchestrationTemplateInfo.getValidationData());
220     vspDetails.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
221     vspDetails.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());*/
222     return vspDetails;
223   }
224
225   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
226
227     errorList.forEach(errorMessage -> {
228       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
229         logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(),
230             vspId));
231       }
232     });
233   }
234
235 }