2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremodule;
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.openecomp.core.utilities.file.FileContentHandler;
25 import org.openecomp.core.utilities.json.JsonUtil;
26 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
27 import org.openecomp.sdc.common.errors.CoreException;
28 import org.openecomp.sdc.common.errors.ErrorCategory;
29 import org.openecomp.sdc.common.errors.ErrorCode;
30 import org.openecomp.sdc.common.errors.Messages;
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.heat.datatypes.manifest.FileData;
35 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
36 import org.openecomp.sdc.heat.datatypes.structure.Artifact;
37 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
38 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao;
39 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory;
40 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
41 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
42 import org.openecomp.sdc.vendorsoftwareproduct.errors.utils.ErrorsUtil;
43 import org.openecomp.sdc.vendorsoftwareproduct.services.HeatFileAnalyzer;
44 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
45 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.ManifestCreator;
46 import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateServiceValidator;
47 import org.openecomp.sdc.vendorsoftwareproduct.types.CandidateDataEntityTo;
48 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles;
49 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
50 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module;
51 import org.openecomp.sdc.versioning.dao.types.Version;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import java.io.ByteArrayInputStream;
56 import java.io.ByteArrayOutputStream;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.nio.ByteBuffer;
60 import java.nio.charset.StandardCharsets;
61 import java.util.ArrayList;
62 import java.util.HashSet;
63 import java.util.List;
65 import java.util.Objects;
66 import java.util.Optional;
68 import java.util.stream.Collectors;
69 import java.util.zip.ZipEntry;
70 import java.util.zip.ZipInputStream;
71 import java.util.zip.ZipOutputStream;
73 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
75 public class CandidateServiceImpl implements CandidateService {
76 protected static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class);
77 private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator();
78 private ManifestCreator manifestCreator;
79 private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao;
81 public CandidateServiceImpl(ManifestCreator manifestCreator,
82 OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao) {
83 this.manifestCreator = manifestCreator;
84 this.orchestrationTemplateCandidateDao = orchestrationTemplateCandidateDao;
88 public CandidateServiceImpl() {
92 public Optional<ErrorMessage> validateNonEmptyFileToUpload(InputStream fileToUpload,
95 getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
98 if (Objects.isNull(fileToUpload)) {
99 return Optional.of(new ErrorMessage(ErrorLevel.ERROR,
103 int available = fileToUpload.available();
104 if (available == 0) {
105 return Optional.of(new ErrorMessage(ErrorLevel.ERROR,
108 } catch (IOException e) {
109 logger.debug(e.getMessage(), e);
110 return Optional.of(new ErrorMessage(ErrorLevel.ERROR,
114 return Optional.empty();
118 public Optional<ErrorMessage> validateRawZipData(String fileSuffix,
119 byte[] uploadedFileData) {
120 if (Objects.isNull(uploadedFileData)) {
121 return Optional.of(new ErrorMessage(ErrorLevel.ERROR,
122 getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
125 return Optional.empty();
128 private String heatStructureTreeToFileDataStructure(HeatStructureTree tree,
129 FileContentHandler zipContentMap,
130 Map<String, List<ErrorMessage>> uploadErrors,
131 AnalyzedZipHeatFiles analyzedZipHeatFiles)
133 FilesDataStructure structure = new FilesDataStructure();
134 Set<String> usedEnvFiles = new HashSet<>();
135 addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors,
136 analyzedZipHeatFiles);
137 handleOtherResources(tree, usedEnvFiles, structure);
138 FilesDataStructure fileDataStructureFromManifest =
139 createFileDataStructureFromManifest(zipContentMap.getFileContent
140 (SdcCommon.MANIFEST_NAME));
141 List<String> structureArtifacts = structure.getArtifacts();
142 structureArtifacts.addAll(fileDataStructureFromManifest.getArtifacts().stream().filter
143 (artifact -> isNotStrctureArtifact(structureArtifacts, artifact))
144 .collect((Collectors.toList())));
145 handleArtifactsFromTree(tree, structure);
147 return JsonUtil.object2Json(structure);
150 private boolean isNotStrctureArtifact(List<String> structureArtifacts, String artifact) {
151 return !structureArtifacts.contains(artifact);
155 public OrchestrationTemplateCandidateData createCandidateDataEntity(
156 CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest,
157 AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception {
158 FileContentHandler zipContentMap = candidateDataEntityTo.getContentMap();
159 FilesDataStructure filesDataStructure;
160 String dataStructureJson;
162 if (zipFileManifest != null) {
163 // create data structure from manifest
164 filesDataStructure = createFileDataStructureFromManifest(zipFileManifest);
165 Set<String> zipFileList = zipContentMap.getFileList();
166 balanceManifestFilesWithZipFiles(filesDataStructure,
167 zipContentMap, analyzedZipHeatFiles);
168 Set<String> filesDataStructureFiles = getFlatFileNames(filesDataStructure);
169 filesDataStructure.getUnassigned().addAll(zipFileList.stream()
170 .filter(fileName -> (!filesDataStructureFiles.contains(fileName) &&
171 !filesDataStructure.getNested().contains(fileName) &&
172 !fileName.equals(SdcCommon.MANIFEST_NAME)))
173 .collect(Collectors.toList()));
174 dataStructureJson = JsonUtil.object2Json(filesDataStructure);
176 // create data structure from based on naming convention
178 heatStructureTreeToFileDataStructure(candidateDataEntityTo.getTree(), zipContentMap,
179 candidateDataEntityTo.getErrors(), analyzedZipHeatFiles);
182 OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData();
183 candidateData.setContentData(ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData()));
184 candidateData.setFilesDataStructure(dataStructureJson);
185 return candidateData;
188 private void balanceManifestFilesWithZipFiles(
189 FilesDataStructure filesDataStructure,
190 FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles)
192 Set<String> zipFileList = fileContentHandler.getFileList();
193 filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles());
194 List<Module> modules = filesDataStructure.getModules();
195 if (CollectionUtils.isEmpty(modules)) {
199 for (int i = 0; i < modules.size(); i++) {
200 Module module = modules.get(i);
201 if (!isFileExistInZipContains(zipFileList, module.getYaml())) {
202 addFileToUnassigned(filesDataStructure, zipFileList, module.getEnv());
203 addFileToUnassigned(filesDataStructure, zipFileList, module.getVol());
204 addFileToUnassigned(filesDataStructure, zipFileList, module.getVolEnv());
206 } else if (Objects.nonNull(module.getVol()) && !zipFileList.contains(module.getVol())) {
209 .addIgnoreNull(filesDataStructure.getUnassigned(), module.getVolEnv());
211 if (filesDataStructure.getNested().contains(module.getYaml())) {
212 moveModuleFileToNested(filesDataStructure, i--, module);
218 private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set<String> zipFileList,
220 if (isFileExistInZipContains(zipFileList, fileName)) {
221 filesDataStructure.getUnassigned().add(fileName);
225 private boolean isFileExistInZipContains(Set<String> zipFileList, String fileName) {
226 return Objects.nonNull(fileName) && zipFileList.contains(fileName);
229 private void moveModuleFileToNested(FilesDataStructure filesDataStructure, int i,
231 if (!filesDataStructure.getNested().contains(module.getYaml())) {
232 filesDataStructure.getNested().add(module.getYaml());
234 if (Objects.nonNull(module.getEnv())) {
235 filesDataStructure.getNested().add(module.getEnv());
237 if (Objects.nonNull(module.getVol())) {
238 filesDataStructure.getNested().add(module.getVol());
240 if (Objects.nonNull(module.getVolEnv())) {
241 filesDataStructure.getNested().add(module.getVolEnv());
243 filesDataStructure.getModules().remove(i);
246 private Set<String> getFlatFileNames(FilesDataStructure filesDataStructure) {
247 Set<String> fileNames = new HashSet<>();
248 if (!CollectionUtils.isEmpty(filesDataStructure.getModules())) {
249 for (Module module : filesDataStructure.getModules()) {
250 CollectionUtils.addIgnoreNull(fileNames, module.getEnv());
251 CollectionUtils.addIgnoreNull(fileNames, module.getVol());
252 CollectionUtils.addIgnoreNull(fileNames, module.getVolEnv());
253 CollectionUtils.addIgnoreNull(fileNames, module.getYaml());
256 fileNames.addAll(filesDataStructure.getArtifacts().stream().collect(Collectors.toSet()));
257 fileNames.addAll(filesDataStructure.getNested().stream().collect(Collectors.toSet()));
258 fileNames.addAll(filesDataStructure.getUnassigned().stream().collect(Collectors.toSet()));
263 private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) {
264 ManifestContent manifestContent =
265 JsonUtil.json2Object(isManifestContent, ManifestContent.class);
266 FilesDataStructure structure = new FilesDataStructure();
267 for (FileData fileData : manifestContent.getData()) {
268 if (Objects.nonNull(fileData.getType()) &&
269 fileData.getType().equals(FileData.Type.HEAT)) {
270 Module module = new Module();
271 module.setYaml(fileData.getFile());
272 module.setIsBase(fileData.getBase());
273 addHeatDependenciesToModule(module, fileData.getData());
274 structure.getModules().add(module);
275 } else if (HeatFileAnalyzer.isYamlOrEnvFile(fileData.getFile()) &&
276 !FileData.Type.isArtifact(fileData.getType())) {
277 structure.getUnassigned().add(fileData.getFile());
279 structure.getArtifacts().add(fileData.getFile());
285 private void addHeatDependenciesToModule(Module module, List<FileData> data) {
286 if (CollectionUtils.isEmpty(data)) {
290 for (FileData fileData : data) {
291 if (fileData.getType().equals(FileData.Type.HEAT_ENV)) {
292 module.setEnv(fileData.getFile());
293 } else if (fileData.getType().equals(FileData.Type.HEAT_VOL))// must be volume
295 module.setVol(fileData.getFile());
296 if (!CollectionUtils.isEmpty(fileData.getData())) {
297 FileData volEnv = fileData.getData().get(0);
298 if (volEnv.getType().equals(FileData.Type.HEAT_ENV)) {
299 module.setVolEnv(volEnv.getFile());
301 throw new CoreException((new ErrorCode.ErrorCodeBuilder())
302 .withMessage(Messages.ILLEGAL_MANIFEST.getErrorMessage())
303 .withId(Messages.ILLEGAL_MANIFEST.getErrorMessage())
304 .withCategory(ErrorCategory.APPLICATION).build());
308 throw new CoreException((new ErrorCode.ErrorCodeBuilder())
309 .withMessage(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage())
310 .withId(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage())
311 .withCategory(ErrorCategory.APPLICATION).build());
317 public void updateCandidateUploadData(String vspId, Version version,
318 OrchestrationTemplateCandidateData uploadData) {
319 orchestrationTemplateCandidateDao.update(vspId, version, uploadData);
323 public Optional<FilesDataStructure> getOrchestrationTemplateCandidateFileDataStructure(
324 String vspId, Version version) {
325 Optional<String> jsonFileDataStructure =
326 orchestrationTemplateCandidateDao.getStructure(vspId, version);
328 if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) {
330 .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class));
332 return Optional.empty();
337 public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version,
338 FilesDataStructure fileDataStructure) {
339 OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface()
340 .updateStructure(vspId, version, fileDataStructure);
344 public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId,
346 return orchestrationTemplateCandidateDao.get(vspId, version);
350 public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidateInfo(String vspId,
352 return orchestrationTemplateCandidateDao.getInfo(vspId, version);
356 public String createManifest(VspDetails vspDetails, FilesDataStructure structure) {
357 Optional<ManifestContent> manifest = manifestCreator.createManifest(vspDetails, structure);
358 if (!manifest.isPresent()) {
359 throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage());
361 return JsonUtil.object2Json(manifest.get());
365 public Optional<ManifestContent> createManifest(VspDetails vspDetails,
366 FileContentHandler fileContentHandler,
367 AnalyzedZipHeatFiles analyzedZipHeatFiles) {
368 return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles);
372 public Optional<ByteArrayInputStream> fetchZipFileByteArrayInputStream(String vspId,
373 OrchestrationTemplateCandidateData candidateDataEntity,
375 OnboardingTypesEnum type,
376 Map<String, List<ErrorMessage>> uploadErrors) {
378 ByteArrayInputStream byteArrayInputStream = null;
380 file = replaceManifestInZip(candidateDataEntity.getContentData(), manifest, vspId, type);
381 byteArrayInputStream = new ByteArrayInputStream(
382 Objects.isNull(file) ? candidateDataEntity.getContentData().array()
384 } catch (IOException e) {
385 ErrorMessage errorMessage =
386 new ErrorMessage(ErrorLevel.ERROR,
387 Messages.CANDIDATE_PROCESS_FAILED.getErrorMessage());
388 logger.error(errorMessage.getMessage(), e);
390 .addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, errorMessage, uploadErrors);
392 return Optional.ofNullable(byteArrayInputStream);
396 public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId,
397 OnboardingTypesEnum type)
399 ByteArrayOutputStream baos = new ByteArrayOutputStream();
401 try (final ZipOutputStream zos = new ZipOutputStream(baos);
402 ZipInputStream zipStream = new ZipInputStream(
403 new ByteArrayInputStream(contentData.array()))) {
405 boolean manifestWritten = false;
406 while ((zipEntry = zipStream.getNextEntry()) != null) {
407 if (!zipEntry.getName().equalsIgnoreCase(SdcCommon.MANIFEST_NAME)) {
408 ZipEntry loc_ze = new ZipEntry(zipEntry.getName());
409 zos.putNextEntry(loc_ze);
410 byte[] buf = new byte[1024];
412 while ((len = zipStream.read(buf)) > 0) {
413 zos.write(buf, 0, (len < buf.length) ? len : buf.length);
416 manifestWritten = true;
417 writeManifest(manifest, type, zos);
421 if (!manifestWritten) {
422 writeManifest(manifest, type, zos);
426 return baos.toByteArray();
430 public Optional<List<ErrorMessage>> validateFileDataStructure(
431 FilesDataStructure filesDataStructure) {
432 return candidateServiceValidator.validateFileDataStructure(filesDataStructure);
435 private void writeManifest(String manifest,
436 OnboardingTypesEnum type,
437 ZipOutputStream zos) throws IOException {
439 if (isManifestNeedsToGetWritten(type)) {
443 zos.putNextEntry(new ZipEntry(SdcCommon.MANIFEST_NAME));
444 try (InputStream manifestStream = new ByteArrayInputStream(
445 manifest.getBytes(StandardCharsets.UTF_8))) {
446 byte[] buf = new byte[1024];
448 while ((len = (manifestStream.read(buf))) > 0) {
449 zos.write(buf, 0, (len < buf.length) ? len : buf.length);
454 private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) {
455 return type.equals(OnboardingTypesEnum.CSAR);
458 private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) {
460 if (Objects.isNull(tree) || Objects.isNull(tree.getArtifacts())) {
464 if (CollectionUtils.isNotEmpty(tree.getArtifacts())) {
465 structure.getArtifacts().addAll(
468 .map(Artifact::getFileName)
469 .filter(fileName -> !structure.getArtifacts().contains(fileName))
470 .collect(Collectors.toList()));
474 private void handleOtherResources(HeatStructureTree tree, Set<String> usedEnvFiles,
475 FilesDataStructure structure) {
476 Set<HeatStructureTree> others = tree.getOther();
477 if (Objects.isNull(others)) {
481 List<String> artifacts = new ArrayList<>();
482 List<String> unassigned = new ArrayList<>();
483 for (HeatStructureTree other : others) {
484 if (HeatFileAnalyzer.isYamlOrEnvFile(other.getFileName())) {
485 if (isEnvFileUsedByHeatFile(usedEnvFiles, other)) {
488 unassigned.add(other.getFileName());
490 artifacts.add(other.getFileName());
492 handleArtifactsFromTree(other, structure);
494 structure.getArtifacts().addAll(artifacts);
495 structure.getUnassigned().addAll(unassigned);
498 private boolean isEnvFileUsedByHeatFile(Set<String> usedEnvFiles, HeatStructureTree other) {
499 if (HeatFileAnalyzer.isEnvFile(other.getFileName())) {
500 if (usedEnvFiles.contains(other.getFileName())) {
507 private void addHeatsToFileDataStructure(HeatStructureTree tree, Set<String> usedEnvFiles,
508 FilesDataStructure structure,
509 Map<String, List<ErrorMessage>> uploadErrors,
510 AnalyzedZipHeatFiles analyzedZipHeatFiles)
512 List<Module> modules = new ArrayList<>();
513 Set<HeatStructureTree> heatsSet = tree.getHeat();
514 if (Objects.isNull(heatsSet)) {
517 for (HeatStructureTree heat : heatsSet) {
518 if (isFileBaseFile(heat.getFileName())) {
519 handleSingleHeat(structure, modules, heat, uploadErrors);
520 } else if (isFileModuleFile(heat.getFileName(),
521 analyzedZipHeatFiles.getModuleFiles())) {
522 handleSingleHeat(structure, modules, heat, uploadErrors);
524 structure.getUnassigned().add(heat.getFileName());
525 addNestedToFileDataStructure(heat, structure);
527 if (!Objects.isNull(heat.getEnv())) {
528 usedEnvFiles.add(heat.getEnv() == null ? null : heat.getEnv().getFileName());
531 structure.setModules(modules);
535 private boolean isFileModuleFile(String fileName, Set<String> modulesFileNames) {
536 return modulesFileNames.contains(fileName);
539 private boolean isFileBaseFile(String fileName) {
540 return manifestCreator.isFileBaseFile(fileName);
543 private void handleSingleHeat(FilesDataStructure structure, List<Module> modules,
544 HeatStructureTree heat,
545 Map<String, List<ErrorMessage>> uploadErrors) {
546 Module module = new Module();
547 module.setYaml(heat.getFileName());
548 module.setIsBase(heat.getBase());
549 addNestedToFileDataStructure(heat, structure);
550 Set<HeatStructureTree> volumeSet = heat.getVolume();
552 if (Objects.nonNull(volumeSet)) {
553 handleVolumes(module, volumeSet, structure, inx, uploadErrors);
555 handleEnv(module, heat, false, structure);
559 private void handleVolumes(Module module, Set<HeatStructureTree> volumeSet,
560 FilesDataStructure structure, int inx,
561 Map<String, List<ErrorMessage>> uploadErrors) {
562 for (HeatStructureTree volume : volumeSet) {
564 ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE,
565 new ErrorMessage(ErrorLevel.WARNING,
566 Messages.MORE_THEN_ONE_VOL_FOR_HEAT.getErrorMessage()), uploadErrors);
569 handleArtifactsFromTree(volume, structure);
570 module.setVol(volume.getFileName());
571 handleEnv(module, volume, true, structure);
572 addNestedToFileDataStructure(volume, structure);
576 private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv,
577 FilesDataStructure structure) {
578 if (Objects.nonNull(tree.getEnv())) {
580 module.setVolEnv(tree.getEnv().getFileName());
582 module.setEnv(tree.getEnv().getFileName());
584 handleArtifactsFromTree(tree.getEnv(), structure);
588 private void addNestedToFileDataStructure(HeatStructureTree heat,
589 FilesDataStructure structure) {
590 Set<HeatStructureTree> nestedSet = heat.getNested();
591 if (Objects.isNull(nestedSet)) {
594 for (HeatStructureTree nested : nestedSet) {
595 if (structure.getNested().contains(nested.getFileName())) {
598 structure.getNested().add(nested.getFileName());
599 if (CollectionUtils.isNotEmpty(nested.getArtifacts())) {
600 handleArtifactsFromTree(nested, structure);
602 addNestedToFileDataStructure(nested, structure);